为什么 foo 函数可以正常工作。
function foo (a,b) {
return arguments.length;
}
但是,即使我在函数中传递了参数,boo 函数返回的 undefined 也不是函数。
function boo (a,b) {
return arguments.slice(0);
}
最佳答案
arguments
不是数组,而是类数组对象。许多数组方法适用于类似数组的对象,因为它们需要一个具有数字属性和 length
属性(例如 arguments
)的对象。您可以通过使用 call
并将对象作为 this
值传递来使用内置函数:
var args = Array.prototype.slice.call(arguments);
//^ args is a real array now
这也适用于其他方法,例如 reduce
:
function sum(/*...args*/) {
return [].reduce.call(arguments, function(x, y){return x + y})
}
关于javascript - 在函数中使用参数对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697054/