为什么foo函数正常工作。在函数中使用参数对象
function foo (a,b) {
return arguments.length;
}
但是,boo函数返回undefined不是一个函数,即使我在函数中传递参数。
function boo (a,b) {
return arguments.slice(0);
}
为什么foo函数正常工作。在函数中使用参数对象
function foo (a,b) {
return arguments.length;
}
但是,boo函数返回undefined不是一个函数,即使我在函数中传递参数。
function boo (a,b) {
return arguments.slice(0);
}
arguments
不是一个数组,但类似阵列的对象。许多数组方法对类似数组的对象起作用,因为它们期望具有数字属性的对象和属性,例如arguments
。
var args = Array.prototype.slice.call(arguments);
//^ args is a real array now
这适用于其他方法,以及像reduce
:您可以通过使用call
和传递对象作为this
值使用内置的功能
function sum(/*...args*/) {
return [].reduce.call(arguments, function(x, y){return x + y})
}
arguments
是一个对象, 不是和array
。如果你打印出来看看,你可以看到一个对象:
function foo (a,b) {
console.log(arguments);
}
foo(10,20);
o/p: { '0': 10, '1': 20 }
从docs,
此对象包含传递给 函数每个参数的入口,第一入口的指数开始0。例如,如果一个 函数传递三个参数,你可以参照参数作为 如下:
arguments[0] arguments[1] arguments[2]
它确实不是具有除length
之外的任何数组属性。
因此,return arguments.slice(0);
将失败,因为slice
属于array
的prototype
。
如何使用切片函数的调用方法将参数对象转换为数组? – mike