欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

將函數(shù)的實(shí)際參數(shù)轉(zhuǎn)換成數(shù)組的方法

 更新時(shí)間:2010年01月25日 20:36:28   作者:  
實(shí)際參數(shù)在函數(shù)中我們可以使用 arguments 對象獲得 (注:形參可通過 arguments.callee 獲得),雖然 arguments 對象與數(shù)組形似,但仍不是真正意義上的數(shù)組。
值得慶幸的是,我們可以通過數(shù)組的 slice 方法將 arguments 對象轉(zhuǎn)換成真正的數(shù)組:
var args = Array.prototype.slice.call(arguments);
對于slice 方法,ECMAScript 262 中 15.4.4.10 Array.prototype.slice (start, end) 章節(jié)有備注:
復(fù)制代碼 代碼如下:

The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.

《Pro JavaScript Design Patterns》(《JavaScript 設(shè)計(jì)模式》)的作者 Dustin Diaz 曾指出:

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

instead of…
var args = Array.prototype.slice.call(arguments); // 懌飛注:下稱方法一
do this…
var args = [].slice.call(arguments, 0); // 懌飛注:下稱方法二

但二者的性能差異真的存在嗎?經(jīng)過個(gè)人簡單測試發(fā)現(xiàn):

在 arguments.length 較小的時(shí)候,方法二性能上稍有一點(diǎn)點(diǎn)優(yōu)勢,而在arguments.length 較大的時(shí)候,方法一卻又稍有優(yōu)勢。

最后附上方法三,最老土的方式:
復(fù)制代碼 代碼如下:

var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}

不過對于平常來說,個(gè)人建議還是使用第二種方法,但任何解決方案,沒有最好的,只有最合適:
復(fù)制代碼 代碼如下:

var args = [].slice.call(arguments, 0);
理由有二:

一般的函數(shù)的 arguments.length 都在 10 以內(nèi),方法二有優(yōu)勢;
方法二的代碼量上也比第一種少,至少可以減小一點(diǎn)字節(jié) ^^

如何將 NodeList (比如:document.getElementsByTagName('div'))轉(zhuǎn)換成數(shù)組呢?

解決方案簡單如下:

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

function nodeListToArray(nodes){
var arr, length;
try {
// works in every browser except IE
arr = [].slice.call(nodes);
return arr;
} catch(err){
// slower, but works in IE
arr = [];
length = nodes.length;
for(var i = 0; i < length; i++){
arr.push(nodes[i]);
}
return arr;
}
}

為什么 IE 中 NodeList 不可以使用 [].slice.call(nodes) 方法轉(zhuǎn)換呢?
In Internet Explorer it throws an error that it can't run Array.prototype.slice.call(nodes) because a DOM NodeList is not a JavaScript object.

相關(guān)文章

最新評論