什么是伪数组?
伪数组,即 arrayLike
,也称为类数组。是一种按照索引存储数据且具有 length
属性的对象。因为是对象,所以不能调用数组的方法,比如 forEach()
、push()
等。
下面的 a
对象就是一个伪数组:
let a = {
0: "x",
1: "y",
2: "z",
length: 3,
};
常见的伪数组有哪些?
- 函数中的
arguments
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
}
-
document.querySelectorAll()
等批量选择元素的方法的返回值
const elements = document.querySelectorAll("div");
console.log(elements); // expected output: NodeList(4) [div, div, div, div]
-
<input/>
文件上传后的files
<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>
如何将伪数组转换为数组?
- ES2015 新增的 Array.from() 方法
let a = {
0: "x",
1: "y",
2: "z",
length: 3,
};
let b = Array.from(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
- 数组的 slice() 方法
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' ]
- 数组的 concat() 方法
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' ]