javascript将函数的实际参数转换成数组

六 29 2010 Published by zdy under 杂七杂八

实际参数在函数中我们可以使用 arguments 对象获得 (注:形参可通过 arguments.callee 获得),虽然 arguments 对象与数组形似,但仍不是真正意义上的数组。

值得庆幸的是,我们可以通过数组的 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);

Related posts:

  1. javascript 小测试[转]
  2. javascript两个数组共同部分,相减
  3. javascript循环调用函数,函数中监听事件只执行最后一个bug
  4. javascript获取网页中鼠标选中的文字或选中指定文字
  5. 做了两个extjs的独立元件

No responses yet

发表评论

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: