|
復(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}
會(huì)發(fā)現(xiàn) associative_array.length 始終等于 0,當(dāng)時(shí)有點(diǎn)迷惑,后來才知道這就像大家認(rèn)為 IE 中支持 CSS 屬性 display:inline-block 一樣,純屬巧合和誤解。
實(shí)際上(引自《JavaScript “Associative Arrays” Considered Harmful》):
There is no way to specify string keys in an array constructor. //在數(shù)組構(gòu)造函數(shù)中無法定義字符串鍵值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ù)字的,鍵值對(duì)應(yīng)使用于對(duì)象上。
There is no way to specify string keys in an array literal. //在數(shù)組字面量中無法定義字符串鍵值
Array.length does not count them as items. // Array.length 不會(huì)計(jì)算字符串鍵值
進(jìn)一步窺探數(shù)組:
1、數(shù)組可以根據(jù)所賦的值自動(dòng)調(diào)整大小
復(fù)制代碼 代碼如下:
var ar = [];
ar[2] = 1;
alert(ar.length)
發(fā)現(xiàn)這個(gè)數(shù)組的長度為 3,就像一個(gè)經(jīng)過初始化的數(shù)組一樣。所有沒有賦值的數(shù)組對(duì)象,都將被定義為 undefined 。
擴(kuò)展閱讀:
- 《Javascript Array Fun》
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ò)展閱讀:
- 《The Miller Device》
- 《isArray: Why is it so bloody hard to get right?》
JavaScript技術(shù):javascript 有趣而詭異的數(shù)組,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。