Array.prototype.slice.call(arguments,[,arg1[arg2]])能将具有length属性的对象转成数组,尤其用于将伪类转换成真正的数组,但是旧版本的IE下用的时候会报错 因为HTMLCollection、NodeList不是Object的子类。
var object1 = {0: 1, 1: 2, length: 2}
console.log(Array.prototype.slice.call(object1));// ["1", "2"]
var fn = function() {
console.log(Array.prototype.slice.call(arguments));//[1,2,3,4,5]
console.log(Array.prototype.slice.call(arguments,1,3));//[2,3]
}
fn(1,2,3,4,5)
复制代码
将伪数组转换为其它数组的方法如下:
- Array.prototype.slice.call(arguments);
- [].slice.call(arguments);
- es6的Array.from(arguments)方法,不接受初始值和结束值
- 兼容性方法
var toArray = function(s){
try{
return Array.prototype.slice.call(s);
} catch(e){
var arr = [];
for(var i = 0,len = s.length; i < len; i++){
arr[i] = s[i];
}
return arr;
}
}
复制代码
Array是类名不是对象名,所以不能直接用Array.slice,而Array.prototype.slice有这个方法所以可以用。[]是实例数组,它的原型链指向Array.prototype.slice,所以Array.prototype.slice === [].slice运行结果是true。 Array.prototype.length等于0,所以不能直接用,通过call把this指向给arguments这样来解决