如何将相同的元素添加到javascript数组n次

Dek*_*eke 9 javascript arrays

var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
Run Code Online (Sandbox Code Playgroud)

而不是推动相同的元素,如何像这样写一次:

fruits.push("lemon" * 4 times)
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 24

对于原语,请使用.fill:

var fruits = new Array(4).fill('Lemon');
console.log(fruits);
Run Code Online (Sandbox Code Playgroud)

对于非基元,不要使用fill,因为那时数组中的所有元素都将引用内存中的同一个对象,因此数组中一个项的突变将影响数组中的每个项 - 相反,在每次迭代时显式创建对象,可以用Array.from:

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));
Run Code Online (Sandbox Code Playgroud)