伪数组(类数组)

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

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

常见的伪数组

函数中的 arguments

1
2
3
4
5
6
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() 等批量选择元素的方法的返回值

1
2
const elements = document.querySelectorAll("div");
console.log(elements); // expected output: NodeList(4) [div, div, div, div]

<input/> 文件上传后的 files

1
2
3
4
5
6
7
8
9
10
11
<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() 方法

1
2
3
4
5
6
7
8
9
let a = {
0: "x",
1: "y",
2: "z",
length: 3,
};

let b = Array.from(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]

数组的 slice() 方法

1
Array.prototype.slice.call(fakeArray)
1
2
3
4
5
6
7
8
9
10
11
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() 方法

1
2
3
4
5
6
7
8
9
let a = {
0: "x",
1: "y",
2: "z",
length: 3,
};

let b = [].concat.apply([], a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]

遍历伪数组的每一项,将其添加到一个新的数组

1
2
3
4
5
6
7
8
9
10
11
12
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' ]