一种按照索引存储数据且具有 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); console.log(arguments.length); }
|
document.querySelectorAll()
等批量选择元素的方法的返回值
1 2
| const elements = document.querySelectorAll("div"); console.log(elements);
|
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); } </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);
|
数组的 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); console.log(c);
|
数组的 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);
|
遍历伪数组的每一项,将其添加到一个新的数组
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);
|