相信很多同学翻看代码的时候都有看到类似下面这个方法
Array.prototype.slice.call()
逐个解析这个方法:
- slice:用来截取截取字符串方法
- Array: javascript的一个引用类型,其原型prototype上有一个方法叫slice
- call和apply : 用来改变对象中函数内部的this引用
综上可以得知这个方法的主要目的是为了将类数组转化为数组
function test(a,b,c,d)
{
var arg = Array.prototype.slice.call(arguments,1);
alert(arg);
}
test("a","b","c","d"); //b,c,d
为什么不直接用 arguments.slice(1)呢 不是一样的么?
Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法
。要是直接写arguments.slice(1)会报错。arguments 是object 不是Array ,他的原型上没有slice方法。
Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)
var a={length:2,0:'first',1:'second'};//类数组,有length属性,长度为2,第0个是first,第1个是second
console.log(Array.prototype.slice.call(a,0));// ["first", "second"],调用数组的slice(0);
var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));//["second"],调用数组的slice(1);
var a={0:'first',1:'second'};//去掉length属性,返回一个空数组
console.log(Array.prototype.slice.call(a,0));//[]
function test(){
console.log(Array.prototype.slice.call(arguments,0));//["a", "b", "c"],slice(0)
console.log(Array.prototype.slice.call(arguments,1));//["b", "c"],slice(1)
}
test("a","b","c");
还有几个其他方法也可以达到类似功能:
1、Array.from
let bar = new Set(['a', 'b', 'c']);
Array.from(bar ); // ['a', 'b', 'c'];
2、扩展运算符[...arg]
function foo(a,b,c,d) {
// console.log(Array.prototype.slice.call(arguments));
// console.log(Array.from(arguments));
console.log([...arguments]); // ["a", "b", "c", "d"]
}
foo("a","b","c","d");
部分参考: https://blog.youkuaiyun.com/astonishqft/article/details/82863315