Array.prototype.slice.appy问题(参数,1)

1)我有以下代码:

var callIt = function(fn) { return fn.apply(this, Array.prototype.slice.apply(arguments, 1)); }; 

当callIt在nodejs中调用时,它会抱怨:

  return fn.apply(this, Array.prototype.slice.apply(arguments, 1)); ^ TypeError: Function.prototype.apply: Arguments list has wrong type 

2)如果我把callIt改成:

 var callIt = function(fn) { return fn.apply(this, Array.prototype.slice.apply(arguments)); }; 

Nodejs不抱怨,但结果不是什么预期的,多余的第一个参数传入。

3)如果我把callIt改成:

 var callIt = function(fn) { var args = Array.prototype.slice.apply(arguments); return Function.prototype.apply(fn, args.slice(1)); //return fn.apply(this, args.slice(1)); //same as above }; 

它按预期工作。

4)如果我在Chrome开发者工具箱中运行testing,像这样:

 > var o={0:"a", 1:"asdf"} undefined > o Object 0: "a" 1: "asdf" __proto__: Object > Array.prototype.slice.call(o,1) [] > Array.prototype.slice.call(o) [] 

现在切片不适用于类似数组的对象。

我对这些感到困惑。 请解释。

我引用了以下内容: Array_generic_methods

你的问题是函数的apply方法需要一个数组作为它的第二个参数 – 这就是你的TypeError来自哪里,你传递了1 。 相反,使用[1]或更好的call方法 :

 fn.apply(this, Array.prototype.slice.call(arguments, 1)); 

之所以没有在{0:"a", 1:"asdf"}是因为这不是一个类似数组的对象 – 它没有length属性。 [].slice.call({0:"a", 1:"asdf", length:2}, 0)会这样做。