将函数的实际参数转换成数组的方法

(编辑:jimmy 日期: 2024/10/10 浏览:2)

值得庆幸的是,我们可以通过数组的 slice 方法将 arguments 对象转换成真正的数组:
var args = Array.prototype.slice.call(arguments);
对于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); // 怿飞注:下称方法一
do this…
var args = [].slice.call(arguments, 0); // 怿飞注:下称方法二

但二者的性能差异真的存在吗?经过个人简单测试发现:

在 arguments.length 较小的时候,方法二性能上稍有一点点优势,而在arguments.length 较大的时候,方法一却又稍有优势。

最后附上方法三,最老土的方式:
复制代码 代码如下:
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}

不过对于平常来说,个人建议还是使用第二种方法,但任何解决方案,没有最好的,只有最合适:
复制代码 代码如下:
var args = [].slice.call(arguments, 0);
理由有二:

一般的函数的 arguments.length 都在 10 以内,方法二有优势;
方法二的代码量上也比第一种少,至少可以减小一点字节 ^^

如何将 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.

一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。