国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

javascript 有趣而詭異的數組

2024-05-06 14:15:50
字體:
來源:轉載
供稿:網友
年前在重寫淘寶旺鋪里的會員卡腳本的時候,無意中發(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ā)現 associative_array.length 始終等于 0,當時有點迷惑,后來才知道這就像大家認為 IE 中支持 CSS 屬性 display:inline-block 一樣,純屬巧合和誤解。

實際上(引自《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.

//大意:數組只支持數字的,鍵值對應使用于對象上。

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

1、數組可以根據所賦的值自動調整大小
代碼如下:
var ar = [];
ar[2] = 1;
alert(ar.length)

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

擴展閱讀:

《Javascript Array Fun》

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

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

“The Miller Device” 的妙用不僅僅在于判斷數組:
代碼如下:
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);
}

擴展閱讀:

《The Miller Device》 《isArray: Why is it so bloody hard to get right?》
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 大庆市| 江孜县| 新宁县| 高青县| 溧水县| 高邑县| 玉山县| 康定县| 哈密市| 花莲县| 崇信县| 岗巴县| 义乌市| 永吉县| 凤阳县| 英吉沙县| 西吉县| 巴塘县| 中超| 惠来县| 武定县| 南投县| 富源县| 南木林县| 姚安县| 汕头市| 双桥区| 阿坝| 乃东县| 正宁县| 福州市| 黔江区| 天气| 河源市| 收藏| 临高县| 嘉祥县| 庆安县| 宝清县| 永仁县| 高平市|