前端攻城狮

JS:什么是伪数组

2021-02-02  本文已影响0人  limengzhe

什么是伪数组?

伪数组,即 arrayLike,也称为类数组。是一种按照索引存储数据且具有 length 属性的对象。因为是对象,所以不能调用数组的方法,比如 forEach()push() 等。

下面的 a 对象就是一个伪数组:

let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

常见的伪数组有哪些?

test(1, 2, 3, 4);

function test() {
  console.log(arguments); // expected output: [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
  console.log(arguments.length); // expected output: 4
}
const elements = document.querySelectorAll("div");
console.log(elements); // expected output: NodeList(4) [div, div, div, div]
<html>
  <body>
    <input type="file" name="file" id="input" onchange="fileChange()" />
  </body>
  <script>
    // 选择文件后触发
    function fileChange() {
      console.log(document.querySelector("#input").files); // expeced output: FileList {0: File, length: 1}
    }
  </script>
</html>

如何将伪数组转换为数组?

let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = Array.from(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [].slice.call(a);
let c = [].slice.apply(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
console.log(c); // expected output: [ 'x', 'y', 'z' ]
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [].concat.apply([], a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [];
for (let i = 0; i < a.length; i++) {
  b.push(a[i]);
}
console.log(b); // expected output: [ 'x', 'y', 'z' ]
上一篇 下一篇

猜你喜欢

热点阅读