Array.prototype.slice.call()方法详解

本文详细介绍了如何在JavaScript中将具有length属性的伪数组,如HTMLCollection和NodeList,转换为真正的数组。探讨了Array.prototype.slice.call()方法的使用,并提供了一种兼容旧版IE的解决方案。

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)

复制代码

将伪数组转换为其它数组的方法如下:

  1. Array.prototype.slice.call(arguments);
  2. [].slice.call(arguments);
  3. es6的Array.from(arguments)方法,不接受初始值和结束值
  4. 兼容性方法
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这样来解决

转载于:https://juejin.im/post/5bc9ad28f265da0aaa054905

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值