如何将函数的实际参数转换成数组
轉自:http://www.planabc.net/2010/01/06/arguments_to_array/
實際參數在函數中我們可以使用 arguments 對象獲得 (注:形參可通過 arguments.callee 獲得),雖然 arguments 對象與數組形似,但仍不是真正意義上的數組。
見(http://hi.baidu.com/lane727/blog/item/f7b9706ca08dcad181cb4aa0.html)
值得慶幸的是,我們可以通過數組的 slice 方法將 arguments 對象轉換成真正的數組:
var args =Array.prototype.slice.call(arguments,0);對于slice 方法,ECMAScript 262 中 15.4.4.10 Array.prototype.slice (start, end) 章節有備注:
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, 0); // 懌飛注:下稱方法一
do this…
var args = [].slice.call(arguments, 0); // 懌飛注:下稱方法二
但二者的性能差異真的存在嗎?經過個人簡單測試發現:
在 arguments.length 較小的時候,方法二性能上稍有一點點優勢,而在arguments.length 較大的時候,方法一卻又稍有優勢。
2010年1月30日更新(測試地址):幾經驗證,性能差異不大,反而第一張方法性能稍優勢一點,或許由于第二種方法創建新數組產生開銷。
最后附上方法三,最老土的方式:
var args =[];for(var i =1; i < arguments.length; i++){
args.push(arguments[i]);
}
不過對于平常來說,個人建議使用第一種方法,但任何解決方案,沒有最好的,只有最合適:
var args =Array.prototype.slice.call(arguments,0);------------------------------------------------------------------
還有一種方式
function a() {var arr = [];
arr = Array.apply(arr, arguments);
alert(arr);
}
a(1);//bug
如何將 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.
轉載于:https://www.cnblogs.com/sking7/archive/2011/12/21/2296133.html
總結
以上是生活随笔為你收集整理的如何将函数的实际参数转换成数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 供应IMX335/IMX386/IMX2
- 下一篇: 几个用于序列化的代码片段