Heim  >  Artikel  >  Web-Frontend  >  将函数的实际参数转换成数组的方法_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 18:35:57875Durchsuche

值得庆幸的是,我们可以通过数组的 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 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 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.
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn