var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
与其推送相同的元素,不如这样编写一次:
fruits.push("lemon" * 4 times)
对于基元,使用.fill
:
var fruits = new Array(4).fill('Lemon');
console.log(fruits);
对于非基元,不要使用fill
,因为这样数组中的所有元素都将引用内存中的同一个对象,因此数组中一项的突变将影响数组中的每一项。
const fruits = new Array(4).fill({ Lemon: 'Lemon' });
fruits[0].Apple = 'Apple';
console.log(JSON.stringify(fruits));
// The above doesn't work for the same reason that the below doesn't work:
// there's only a single object in memory
const obj = { Lemon: 'Lemon' };
const fruits2 = [];
fruits2.push(obj);
fruits2.push(obj);
fruits2.push(obj);
fruits2.push(obj);
fruits2[0].Apple = 'Apple';
console.log(JSON.stringify(fruits2));
相反,在每次迭代时显式创建对象,这可以通过Array.from
:
var fruits = Array.from(
{ length: 4 },
() => ({ Lemon: 'Lemon' })
);
console.log(fruits);
有关如何以这种方式创建二维数组的示例:
var fruits = Array.from(
{ length: 2 }, // outer array length
() => Array.from(
{ length: 3 }, // inner array length
() => ({ Lemon: 'Lemon' })
)
);
console.log(fruits);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)