又是一个小小知识点,话不多少,先看代码。
const cars1= new Array("Saab", "Volvo", "BMW");
//['Saab', 'Volvo', 'BMW']
const cars2 = new Array(3)
//[empty × 3]
cars2.length
//3
const cars3 = new Array(3,2)
//[3, 2]
const cars4 = new Array(null)
//[null]
显而易见,如果只传入一个数字的话3
,会生成一个长度为3
的数组,数据项都为empty
。
再看来一个特殊场景
const cars = new Array(3);
cars.A = '新能源汽车';
console.log(cars);
// [empty × 3, A: '新能源汽车']
cars.length;
// 3
const names = new Array('tom','lihua');
names.A = 'LK';
console.log(names);
// ['tom', 'lihua', A: 'LK']
names.length;
// 2
names.forEach(name => {
console.log(name)
})
// tom lihua
for(var i in names){
console.log(names[i])
}
// tom lihua LK
可以看出通过点操作符(.)
添加的属性和length
属性处于同一层级,不会影响length
的值。
且通过点操作符(.)
添加的属性可以用for...in...
循环遍历,但不能用forEach
循环遍历。