如何将函数的实际参数转换成数组
轉(zhuǎn)自:http://www.planabc.net/2010/01/06/arguments_to_array/
實(shí)際參數(shù)在函數(shù)中我們可以使用 arguments 對(duì)象獲得 (注:形參可通過(guò) arguments.callee 獲得),雖然 arguments 對(duì)象與數(shù)組形似,但仍不是真正意義上的數(shù)組。
見(jiàn)(http://hi.baidu.com/lane727/blog/item/f7b9706ca08dcad181cb4aa0.html)
值得慶幸的是,我們可以通過(guò)數(shù)組的 slice 方法將 arguments 對(duì)象轉(zhuǎn)換成真正的數(shù)組:
var args =Array.prototype.slice.call(arguments,0);對(duì)于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 設(shè)計(jì)模式》)的作者 Dustin Diaz 曾指出:
instead of…
var args = Array.prototype.slice.call(arguments, 0); // 懌飛注:下稱(chēng)方法一
do this…
var args = [].slice.call(arguments, 0); // 懌飛注:下稱(chēng)方法二
但二者的性能差異真的存在嗎?經(jīng)過(guò)個(gè)人簡(jiǎn)單測(cè)試發(fā)現(xiàn):
在 arguments.length 較小的時(shí)候,方法二性能上稍有一點(diǎn)點(diǎn)優(yōu)勢(shì),而在arguments.length 較大的時(shí)候,方法一卻又稍有優(yōu)勢(shì)。
2010年1月30日更新(測(cè)試地址):幾經(jīng)驗(yàn)證,性能差異不大,反而第一張方法性能稍?xún)?yōu)勢(shì)一點(diǎn),或許由于第二種方法創(chuàng)建新數(shù)組產(chǎn)生開(kāi)銷(xiāo)。
最后附上方法三,最老土的方式:
var args =[];for(var i =1; i < arguments.length; i++){
args.push(arguments[i]);
}
不過(guò)對(duì)于平常來(lái)說(shuō),個(gè)人建議使用第一種方法,但任何解決方案,沒(mé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'))轉(zhuǎn)換成數(shù)組呢?
解決方案簡(jiǎn)單如下:
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.
轉(zhuǎn)載于:https://www.cnblogs.com/sking7/archive/2011/12/21/2296133.html
總結(jié)
以上是生活随笔為你收集整理的如何将函数的实际参数转换成数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 供应IMX335/IMX386/IMX2
- 下一篇: 几个用于序列化的代码片段