我知道它是用来使参数成为一个真正的数组,但我不明白当使用Array.prototype.slice.call(参数);时会发生什么。
当前回答
array. prototype.slice.call(参数)是将参数转换为数组的老式方法。
在ECMAScript 2015中,你可以使用Array.from或展开操作符:
let args = Array.from(arguments);
let args = [...arguments];
其他回答
假设你有:function。apply(thisArg, argArray)
apply方法调用一个函数,传入将绑定到this的对象 和一个可选的参数数组。
slice()方法选择数组的一部分,并返回新数组。
当你调用array。prototype。slice。Apply (arguments,[0])在参数上调用数组切片方法(bind)。
正如MDN所指出的,这是因为
arguments对象不是数组。它类似于数组,但是 除了长度以外,没有任何数组属性。例如,它确实如此 没有pop方法。然而,它可以转换为一个真正的数组:
这里我们是在原生对象Array上调用slice,而不是在它的实现上调用slice,这就是为什么要使用额外的.prototype
var args = Array.prototype.slice.call(arguments);
通常,调用
var b = a.slice();
将数组a复制到b中。然而,我们不能
var a = arguments.slice();
因为参数没有slice作为方法(它不是一个真正的数组)。
Array.prototype.slice是数组的slice函数。.call运行这个slice函数,并将this值设置为参数。
Array.prototype.slice=function(start,end){
let res=[];
start=start||0;
end=end||this.length
for(let i=start;i<end;i++){
res.push(this[i])
}
return res;
}
当你这样做时:
Array.prototype.slice.call(arguments)
Arguments在slice中变成this的值,然后slice返回一个数组
arguments对象实际上不是Array的实例,也没有任何Array方法。因此,arguments.slice(…)将不起作用,因为arguments对象没有slice方法。
数组确实有这个方法,因为arguments对象与数组非常相似,所以两者是兼容的。这意味着我们可以在arguments对象中使用数组方法。由于数组方法是在考虑数组的情况下构建的,因此它们将返回数组而不是其他参数对象。
为什么使用array。prototype呢?Array是我们用来创建新数组的对象(new Array()),这些新数组被传递方法和属性,比如slice。这些方法存储在[Class]中。原型对象。因此,为了提高效率,我们不通过(new Array()).slice.call()或[].slice.call()来访问slice方法,而是直接从原型中获取它。这样我们就不必初始化一个新数组。
But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.