2019-04-18将类数组对象转换成数组的方法总结

  1. Array.prototype.slice.call(类数组对象)
    例1: function foo(a, b) {
    let res = Array.prototype.slice.call(arguments);
    console.log(res);
    }

foo('aaa', 'bbb'); //(2) ["aaa", "bbb"]

例2: let json = {
0: 'aaa',
1: 'bbb',
2: 'ccc',
length: 3
}
let res = Array.prototype.slice.call(json);
console.log(res); //(3) ["aaa", "bbb", "ccc"]

  1. Array.from(类数组对象)
    例1:function foo(a, b) {
    let res = Array.from(arguments);
    console.log(res);
    }
    foo('aaa', 'bbb'); //(2) ["aaa", "bbb"]

例2: let json = {
0: 'aaa',
1: 'bbb',
2: 'ccc',
length: 3
}
let res = Array.from(json);
console.log(res); //(3) ["aaa", "bbb", "ccc"]

  1. 扩展运算符
    例1: function foo(a, b) {
    let res = [...arguments];
    console.log(res);
    }
    foo('aaa', 'bbb'); //(2) ["aaa", "bbb"]

注:扩展运算符不能将json格式的类数组对象转化成数组!!!

   let json = {
        0: 'aaa',
        1: 'bbb',
        2: 'ccc',
        length: 3
    }
    let res = [...json];
    console.log(res);     Uncaught TypeError: json is not iterable at 类数组转数组.html:22
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容