1 类数组/伪数组
let div1 = document.getElementsByTagName('div');
console.log('div1:', div1); // []
console.log('div1 lenth:', div1.length); // 0
div1.push(1); // 报错 TypeError: div1.push is not a function
2 slice将伪数组转数组
let div1 = document.getElementsByTagName('div');
let arr = Array.prototype.slice.call(div1);
console.log(arr)
arr.push(1)
console.log('arr', arr)
3 Array.from()
let arrayLike = {
0: 'es6',
1: 'es7',
2: 'es8',
length: 3,
};
let arr = Array.from(arrayLike);
arr.push('es9');
console.log(arr); // ["es6", "es7", "es8", "es9"]
4 Array.of()
let arr = Array.of(1, 2);
console.log(arr); // [1, 2]
let arr = Array.of(3);
console.log(arr); // [3]
5 copyWithin()
let arr = [1, 2, 3, 4, 5];
console.log(arr.copyWithin(1, 3)) // [1, 4, 5, 4, 5]
6 fill()
let arr = new Array(3).fill(7)
console.log(arr) //[7, 7, 7]
let arr = [1, 2, 3, 4, 5];
arr.fill('imooc', 1, 3);
console.log(arr); //[1, "imooc", "imooc", 4, 5]
7 includes()
let arr = [1, 2, 3, NaN];
console.log(arr.indexOf(NaN)) // indexOf 不可以检测NaN
console.log(arr.includes(NaN)) // includes 可以检测NaN
网友评论