亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

javascript 有趣而詭異的數(shù)組

 更新時間:2009年04月06日 00:59:32   作者:  
javascript 有趣而詭異的數(shù)組
年前在重寫淘寶旺鋪里的會員卡腳本的時候,無意中發(fā)現(xiàn)了一個有趣的事情。代碼類似:
復(fù)制代碼 代碼如下:

var associative_array = new Array();
associative_array["one"] = "1";
associative_array["two"] = "2";
associative_array["three"] = "3";
if(associative_array.length > 0)
{ // to do}

會發(fā)現(xiàn) associative_array.length 始終等于 0,當(dāng)時有點(diǎn)迷惑,后來才知道這就像大家認(rèn)為 IE 中支持 CSS 屬性 display:inline-block 一樣,純屬巧合和誤解。

實(shí)際上(引自《JavaScript “Associative Arrays” Considered Harmful》):

JavaScript arrays (which are meant to be numeric) are often used to hold key/value pairs. This is bad practice. Object should be used instead.

//大意:數(shù)組只支持?jǐn)?shù)字的,鍵值對應(yīng)使用于對象上。

There is no way to specify string keys in an array constructor. //在數(shù)組構(gòu)造函數(shù)中無法定義字符串鍵值
There is no way to specify string keys in an array literal. //在數(shù)組字面量中無法定義字符串鍵值
Array.length does not count them as items. // Array.length 不會計算字符串鍵值
進(jìn)一步窺探數(shù)組:

1、數(shù)組可以根據(jù)所賦的值自動調(diào)整大小
復(fù)制代碼 代碼如下:

var ar = [];
ar[2] = 1;
alert(ar.length)

發(fā)現(xiàn)這個數(shù)組的長度為 3,就像一個經(jīng)過初始化的數(shù)組一樣。所有沒有賦值的數(shù)組對象,都將被定義為 undefined 。

擴(kuò)展閱讀:

2、可使用 “The Miller Device” 方法來判斷是否是數(shù)組

復(fù)制代碼 代碼如下:

function isArray(o) { return Object.prototype.toString.call(o) === '[object Array]';}

“The Miller Device” 的妙用不僅僅在于判斷數(shù)組:
復(fù)制代碼 代碼如下:

var is = {
types : ["Array","RegExp","Date","Number","String","Object"]
};

for(var i=0,c;c=is.types[i++];){
is[c] = (function(type){
return function(obj){
return Object.prototype.toString.call(obj) == “[object "+type+"]“;
}
})(c);
}

擴(kuò)展閱讀:

相關(guān)文章

最新評論