长度
JS 数组长度不是里面包含了多少个元素,为数组中元素最大索引加一
const arr = [];
arr[20] = 1;
console.log(arr.length)
console.log(arr[0])
let arr1 = [1, 2, 3, 4, 5, 6, 7];
arr1.length = 4;
console.log(arr1)
arr1.length = 0;
console.log(arr1);
遍历
使用 for…in 和 forEach() 遍历都会跳过空元素(undefine) 使用 for…of 和 for 遍历,依然会遍历空元素
let arr = [1, 2];
arr[5] = 5;
for(let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for(let site of arr) {
console.log(site)
}
for(let key in arr) {
console.log(arr[key]);
}
arr.forEach(value => {
console.log(value);
})
关于数组的计算属性
const arr = [];
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr["property" + "1"] = "数组的计算属性";
console.log(arr.property1);
for(let index in arr) {
console.log(arr[index]);
}
console.log(arr.length);
不要使用 === 去判断数组相等,或判断否空数组
记住,数组也是对象
const arr= []
console.log(arr === []);
console.log(arr === 0);
console.log([1] === [1])
console.log(arr == 0)
console.log(arr == '')
console.log(arr == [])
console.log(arr == null)
console.log([1] == [1])
|