关于前端:Js-new-Array

32次阅读

共计 646 个字符,预计需要花费 2 分钟才能阅读完成。

又是一个小小知识点,话不多少,先看代码。

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 循环遍历。

正文完
 0