关于前端:Js-new-Array

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

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理