Javascript'参数'关键字 [英] Javascript 'arguments' Keyword
问题描述
我的理解是我可以调用 Array.prototype.slice.call(arguments,1)
来返回数组的尾部。
My understanding is that I can call Array.prototype.slice.call(arguments, 1)
to return the tail of an array.
为什么这段代码不会返回 [2,3,4,5]
?
Why won't this code return [2,3,4,5]
?
function foo() {
return Array.prototype.slice.call(arguments,1);
}
alert(foo([1,2,3,4,5]));
推荐答案
因为你只传递一个论证—数组。
Because you're only passing one argument — the array.
尝试 alert(foo(1,2,3,4,5));
在JavaScript中,参数从0开始编号,因此当你从1开始切片并传递1个参数时,你什么也得不到。
Arguments are numbered from 0 in JavaScript, so when you start your slice at 1 and pass 1 argument, you get nothing.
请注意,它可能会妨碍优化,允许参数
对象泄漏出函数。由于 arguments
和形式参数之间的别名,如果参数$ c,优化器无法对函数进行任何静态分析$ c>对象被发送到其他地方,因为它不知道参数变量会发生什么。
Note that it can hamper optimization to allow the arguments
object to "leak" out of a function. Because of the aliasing between arguments
and the formal parameters, an optimizer can't really do any static analysis of the function if the arguments
object gets sent somewhere else, because it has no idea what might happen to the parameter variables.
这篇关于Javascript'参数'关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!