|
var args = Array.prototype.slice.call(arguments);
對于slice 方法,ECMAScript 262 中 15.4.4.10 Array.prototype.slice (start, end) 章節(jié)有備注:
復制代碼 代碼如下:
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 設計模式》)的作者 Dustin Diaz 曾指出:
復制代碼 代碼如下:
instead of…
var args = Array.prototype.slice.call(arguments); // 懌飛注:下稱方法一
do this…
var args = [].slice.call(arguments, 0); // 懌飛注:下稱方法二
但二者的性能差異真的存在嗎?經過個人簡單測試發(fā)現:
在 arguments.length 較小的時候,方法二性能上稍有一點點優(yōu)勢,而在arguments.length 較大的時候,方法一卻又稍有優(yōu)勢。
最后附上方法三,最老土的方式:
復制代碼 代碼如下:
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
不過對于平常來說,個人建議還是使用第二種方法,但任何解決方案,沒有最好的,只有最合適:
復制代碼 代碼如下:
var args = [].slice.call(arguments, 0);
理由有二:
一般的函數的 arguments.length 都在 10 以內,方法二有優(yōu)勢;
方法二的代碼量上也比第一種少,至少可以減小一點字節(jié) ^^
如何將 NodeList (比如:document.getElementsByTagName('div'))轉換成數組呢?
解決方案簡單如下:
復制代碼 代碼如下:
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) 方法轉換呢?
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.
JavaScript技術:將函數的實際參數轉換成數組的方法,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。