我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。
当前回答
别忘了,这种行为的底层基础是完全集成在js引擎中的类型转换。
Slice只接受object(多亏了已有的参数。Length属性),并在对其执行所有操作后返回数组对象。
如果你试图用INT-value来处理String-method,你可以测试相同的逻辑:
String.prototype.bold.call(11); // returns "<b>11</b>"
这就解释了上面的表述。
其他回答
它使用slice方法数组have并调用它,它的this是arguments对象。这意味着它会像调用arguments.slice()一样调用它,假设参数有这样一个方法。
创建一个不带任何参数的切片将简单地获取所有元素——因此它只是简单地将元素从参数复制到数组中。
通常,调用
var b = a.slice();
将数组a复制到b中。然而,我们不能
var a = arguments.slice();
因为参数没有slice作为方法(它不是一个真正的数组)。
Array.prototype.slice是数组的slice函数。.call运行这个slice函数,并将this值设置为参数。
// 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]
假设你有: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];