我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。


当前回答

// We can apply `slice` from  `Array.prototype`:
Array.prototype.slice.call([]); //-> []

// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true

// … we can just invoke it directly:
[].slice(); //-> []

// `arguments` has no `slice` method
'slice' in arguments; //-> false

// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]

// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]

其他回答

// We can apply `slice` from  `Array.prototype`:
Array.prototype.slice.call([]); //-> []

// Since `slice` is available on an array's prototype chain,
'slice' in []; //-> true
[].slice === Array.prototype.slice; //-> true

// … we can just invoke it directly:
[].slice(); //-> []

// `arguments` has no `slice` method
'slice' in arguments; //-> false

// … but we can apply it the same way:
Array.prototype.slice.call(arguments); //-> […]

// In fact, though `slice` belongs to `Array.prototype`,
// it can operate on any array-like object:
Array.prototype.slice.call({0: 1, length: 1}); //-> [1]

别忘了,这种行为的底层基础是完全集成在js引擎中的类型转换。

Slice只接受object(多亏了已有的参数。Length属性),并在对其执行所有操作后返回数组对象。

如果你试图用INT-value来处理String-method,你可以测试相同的逻辑:

String.prototype.bold.call(11);  // returns "<b>11</b>"

这就解释了上面的表述。

假设你有:function。apply(thisArg, argArray)

apply方法调用一个函数,传入将绑定到this的对象 和一个可选的参数数组。

slice()方法选择数组的一部分,并返回新数组。

当你调用array。prototype。slice。Apply (arguments,[0])在参数上调用数组切片方法(bind)。

array. prototype.slice.call(参数)是将参数转换为数组的老式方法。

在ECMAScript 2015中,你可以使用Array.from或展开操作符:

let args = Array.from(arguments);

let args = [...arguments];

当正常调用.slice()时,这是一个数组,然后它只是迭代该数组,并完成它的工作。

 //ARGUMENTS
function func(){
  console.log(arguments);//[1, 2, 3, 4]

  //var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
  var arrArguments = [].slice.call(arguments);//cp array with explicity THIS  
  arrArguments.push('new');
  console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]