Array.prototype.slice 使用擴(kuò)展
2024-09-06 12:45:48
供稿:網(wǎng)友
除了正常用法,slice 經(jīng)常用來將 array-like 對(duì)象轉(zhuǎn)換為 true array.
名詞解釋:array-like object – 擁有 length 屬性的對(duì)象,比如 { 0: ‘foo', length: 1 }, 甚至 { length: ‘bar' }. 最常見的 array-like 對(duì)象是 arguments 和 NodeList.
查看 V8 引擎 array.js 的源碼,可以將 slice 的內(nèi)部實(shí)現(xiàn)簡(jiǎn)化為:
代碼如下:
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ù)值時(shí),ToUnit32(this.length) 返回 0.
對(duì)于標(biāo)準(zhǔn)瀏覽器,上面已經(jīng)將 slice 的原理解釋清楚了。但是惱人的 ie, 總是給我們添亂子:
代碼如下:
var slice = Array.prototype.slice;
slice.call(); // => IE: Object expected.
slice.call(document.childNodes); // => IE: JScript object expected.
以上代碼,在 ie 里報(bào)錯(cuò)??珊?IE 的 Trident 引擎不開源,那我們只有猜測(cè)了:
代碼如下:
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, 還有一個(gè)話題:用 Array.prototype.slice 還是 [].slice ? 從理論上講,[] 需要?jiǎng)?chuàng)建一個(gè)數(shù)組,性能上會(huì)比 Array.prototype 稍差。但實(shí)際上,這兩者差不多,就如循環(huán)里用 i++ 還是 ++i 一樣,純屬個(gè)人習(xí)慣。
最后一個(gè)話題,有關(guān)性能。對(duì)于數(shù)組的篩選來說,有一個(gè)犧牲色相的寫法:
代碼如下:
var ret = [];
for(var i = start, j = 0; i < end; i++) {
ret[j++] = arr[i];
}
用空間換時(shí)間。去掉 push, 對(duì)于大數(shù)組來說,性能提升還是比較明顯的。
一大早寫博,心情不是很好,得留個(gè)題目給大家:
代碼如下:
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]); // ?