什么是JS的伪/类数组?如何转为标准数组?

79 阅读1分钟

一、什么是JS的伪/类数组?

  1. 有length属性
  2. 按索引排序
  3. 不能使用数组方法
  4. 可以使用for循环

如何转为标准数组

  1. Array.prototype.slice.call(arguments)
  2. Array.prototype.splice.call(arguments, 0)
  3. Array.from(arguments)
  4. Array.prototype.concat.apply([], arguments)

三、示例

window.onload = function() {
    function nodeList() {
        // 方法一: Array.prototype.slice.call(arguments)
        // 方法二: Array.prototype.splice.call(arguments)
        // 方法三: Array.prototype.concat.apply([],arguments)
        // 方法四: Array.from(arguments)
       return Array.prototype.slice.call(arguments);
    }
    let arr = nodeList(1, 2, 3, 4, 5, 6, 7);
    arr.push(20);
    console.log('arr:', arr);
}