我的理解是,我可以打电话给Array.prototype.slice.call(arguments, 1)
返回数组的尾部。的Javascript“参数”关键字
为什么不这段代码返回[2,3,4,5]
?
function foo() {
return Array.prototype.slice.call(arguments,1);
}
alert(foo([1,2,3,4,5]));
我的理解是,我可以打电话给Array.prototype.slice.call(arguments, 1)
返回数组的尾部。的Javascript“参数”关键字
为什么不这段代码返回[2,3,4,5]
?
function foo() {
return Array.prototype.slice.call(arguments,1);
}
alert(foo([1,2,3,4,5]));
因为你只有通过一个参数—数组。
尝试alert(foo(1,2,3,4,5));
参数从0 JavaScript的编号,所以当你从1开始你的片,并通过1周的说法,你什么也得不到。
注意,它会妨碍优化,使arguments
对象“泄漏”出来的功能。由于arguments
与形式参数之间的混叠,如果对象被发送到其他地方,优化器不能真正对该函数进行任何静态分析,因为它不知道参数变量会发生什么情况。
由于arguments
是{0: [1,2,3,4,5], length: 1}
,这与一个元素的数组状物体。具有一个元素的数组的尾部是空数组。
要么改变函数的定义:
function foo(arr) {
return Array.prototype.slice.call(arr,1);
}
或调用该函数:
foo(1,2,3,4,5);
arguments
是阵列状物体,其中列出了参数和其他一些性质(例如作为参考arguments.callee
中的当前函数)。
在这种情况下,您的arguments
物体看起来是这样的:
arguments {
0: [1,2,3,4,5],
length: 1,
other properties here
}
我觉得这个解释你看到很好的行为。尝试删除函数调用中的数组括号,或使用arguments[0]
来访问该arry。
它会更好,然后,复制的论点? '函数foo(){ \t变参=参数; \t return Array.prototype.slice.call(args,1); }' – Eric 2016-05-16 17:45:23
关于'arguments'关键字的MDN文章描述了您提到的这个优化问题:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – Eric 2016-05-16 17:50:07