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

javascript Array.prototype.slice使用說明

 更新時間:2010年10月11日 22:40:50   作者:  
slice 可以用來獲取數(shù)組片段,它返回新數(shù)組,不會修改原數(shù)組。
除了正常用法,slice 經(jīng)常用來將 array-like 對象轉(zhuǎn)換為 true array.

名詞解釋:array-like object – 擁有 length 屬性的對象,比如 { 0: ‘foo', length: 1 }, 甚至 { length: ‘bar' }. 最常見的 array-like 對象是 arguments 和 NodeList.

查看 V8 引擎 array.js 的源碼,可以將 slice 的內(nèi)部實現(xiàn)簡化為:

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

function slice(start, end) {
var len = ToUint32(this.length), result = [];
for(var i = start; i < end; i++) {
result.push(this[i]);
}
return result;
}


可以看出,slice 并不需要 this 為 array 類型,只需要有 length 屬性即可。并且 length 屬性可以不為 number 類型,當(dāng)不能轉(zhuǎn)換為數(shù)值時,ToUnit32(this.length) 返回 0.

對于標(biāo)準(zhǔn)瀏覽器,上面已經(jīng)將 slice 的原理解釋清楚了。但是惱人的 ie, 總是給我們添亂子:
復(fù)制代碼 代碼如下:

var slice = Array.prototype.slice;
slice.call(); // => IE: Object expected.
slice.call(document.childNodes); // => IE: JScript object expected.

以上代碼,在 ie 里報錯??珊?IE 的 Trident 引擎不開源,那我們只有猜測了:
復(fù)制代碼 代碼如下:

function ie_slice(start, end) {
var len = ToUint32(this.length), result = [];

if(__typeof__ this !== 'JScript Object') throw 'JScript object expected';
if(this === null) throw 'Oject expected';

for(var i = start; i < end; i++) {
result.push(this[i]);
}
return result;
}

至此,把猥瑣的 ie 自圓其說完畢。

關(guān)于 slice, 還有一個話題:用 Array.prototype.slice 還是 [].slice ? 從理論上講,[] 需要創(chuàng)建一個數(shù)組,性能上會比 Array.prototype 稍差。但實際上,這兩者差不多,就如循環(huán)里用 i++ 還是 ++i 一樣,純屬個人習(xí)慣。

最后一個話題,有關(guān)性能。對于數(shù)組的篩選來說,有一個犧牲色相的寫法:
復(fù)制代碼 代碼如下:

var ret = [];
for(var i = start, j = 0; i < end; i++) {
ret[j++] = arr[i];
}

用空間換時間。去掉 push, 對于大數(shù)組來說,性能提升還是比較明顯的。

一大早寫博,心情不是很好,得留個題目給大家:
復(fù)制代碼 代碼如下:

var slice = Array.prototype.slice;
alert(slice.call({0: 'foo', length: 'bar'})[0]); // ?
alert(slice.call(NaN).length); // ?
alert(slice.call({0: 'foo', length: '100'})[0]); // ?

相關(guān)文章

最新評論