国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表

圖片精選

主站蜘蛛池模板: 黔西县| 邳州市| 黄山市| 习水县| 红桥区| 永登县| 都匀市| 延庆县| 穆棱市| 英德市| 新营市| 司法| 晋州市| 建昌县| 吴忠市| 通海县| 平阴县| 盖州市| 广元市| 梅河口市| 三门县| 兴城市| 喜德县| 景德镇市| 桂阳县| 东乡| 习水县| 平山县| 积石山| 南郑县| 邢台市| 大荔县| 藁城市| 寻甸| 当涂县| 黄陵县| 中卫市| 鸡泽县| 东光县| 永定县| 伊川县|