为什么切片不能直接在参数上工作?

时间:2013-05-02 19:00:21

标签: javascript underscore.js

在查看fiddle

后,在underscore.上对其进行了测试

当它不在原型链上时,这似乎是在arguments上调用切片的黑客。

当它明显适用于arguments.

时,为什么它不在原型链上
var slice = Array.prototype.slice;
function test () {
    return slice.call(arguments,1);
    // return arguments.slice(1)
}
var foo = test(1,2,3,4);
_.each(foo, function(val){
    console.log(val)
});

4 个答案:

答案 0 :(得分:4)

>>> Object.prototype.toString.call(arguments)
<<< "[object Arguments]"
>>> Array.isArray(arguments) //is not an array
<<< false
>>> arguments instanceof Array //does not inherit from the Array prototype either
<<< false

arguments不是Array对象,也就是说,它不会从Array原型继承。但是,它包含类似于数组的结构(数字键和length属性),因此Array.prototype.slice可以应用于它。这称为duck typing

哦,当然,Array.prototype.slice总是返回array,因此它可以用于将类似数组的对象/集合转换为新的数组。 ref: MDN Array slice method - Array-like objects)功能

答案 1 :(得分:0)

参数不是“真正的”数组。

  

arguments对象是一个可用的局部变量   功能;作为Function属性的参数不能再使用了。

     

arguments对象不是Array。它类似于数组,但是   除了length之外没有任何Array属性。例如,确实如此   没有pop方法。但是它可以转换为真正的数组。

你可以这样做:

var args = Array.prototype.slice.call(arguments);

答案 2 :(得分:0)

参数不是数组。这是一个Arguments对象。

幸运的是,slice只需要一个类似于Array的对象,并且由于Arguments具有长度和数字索引属性,slice.call(arguments)仍然有效。

是一个黑客,但它在任何地方都是安全的。

答案 3 :(得分:0)

参考MDN:»arguments对象不是Array。它类似于Array,但除了length之外没有任何Array属性。例如,它没有pop方法。但是它可以转换为真正的数组:«

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

为了调用 slice ,你必须从Array-prototype获得slice函数。

相关问题