JS 常见伪数组及转为数组方法

一、伪数组(类数组)特点

1、具有length属性;

2、可以使用下标访问数据;

3、不具有数组的方法, 比如push()、pop()等。

二、常见伪数组

1、字符串:

    let str = 'hello';
    console.log(str.length) // 5
    console.log(str[1]) // e

2、function的arguments对象:

    let fun = function() {
        console.log(arguments.length); // 3
        console.log(arguments[1]);  // 2
    }

    fun(1, 2, "abc");

3、含有length属性的对象:

    let obj = {
        length : 2
    };

    console.log(obj.length);  // 2
    console.log(obj[1]);  // undefined
    obj[1] = 'hello';  
    console.log(obj); // {1: 'hello', length: 2}

三、伪数组转为数组的方法

1、使用Array.prototype.slice.call()或者Array.prototype.slice.apply();

2、使用[].slice.call()或者[].slice.apply();这种方法和上面的方法是一样的,但是上面的方式效率相对较高;

3、使用Array.from();

4、使用Array.of();

5、使用new Array();

    let str = 'hello';
    console.log(str.length) // 5
    console.log(str[1]) // e
    
    console.log(Array.prototype.slice.call(str)) // ['h', 'e', 'l', 'l', 'o']
    console.log(Array.prototype.slice.apply(str)) // ['h', 'e', 'l', 'l', 'o']
    console.log(Array.from(str)); // ['h', 'e', 'l', 'l', 'o']  
    console.log(Array.of(...str)); // ['h', 'e', 'l', 'l', 'o']    
    console.log(new Array(...str)); // ['h', 'e', 'l', 'l', 'o']  
     

    let fun = function() {
        console.log(arguments.length); // 3
        console.log(arguments[1]);  // 2

        console.log([].slice.call(arguments));  // [1, 2, 'abc']
        console.log([].slice.apply(arguments));  // [1, 2, 'abc']        
        console.log(Array.from(arguments)); // [1, 2, 'abc']
        console.log(Array.of(...arguments)); // [1, 2, 'abc']
        console.log(new Array(...arguments)); // [1, 2, 'abc']
    }

    fun(1, 2, "abc");


    let obj = {
        length : 2
    };

    console.log(obj.length);  // 2
    console.log(obj[1]);  // undefined
    obj[1] = 'hello';  
    console.log(obj); // {1: 'hello', length: 2}

    console.log(Array.prototype.slice.call(obj));  // [empty, 'hello']
    console.log([].slice.call(obj));  // [empty, 'hello']
    console.log(Array.from(obj)); //[undefined, 'hello']
    // console.log(Array.of(...obj)); // TypeError: Found non-callable @@iterator
    // console.log(new Array(...obj)); // TypeError: Found non-callable @@iterator

参考文章

js中伪数组(也叫类数组)_Afterwade的博客-CSDN博客_js中的伪数组

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值