var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");
而不是推入相同的元素,如何像这样写一次:
fruits.push("lemon" * 4 times)
发布于 2018-08-14 07:56:14
对于原语,请使用.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);
发布于 2018-08-14 08:00:23
发布于 2021-03-13 18:58:16
const item = 'lemon'
const arr = Array.from({length: 10}, () => item)
const item = 'lemon'
const arr = Array.from({length: 10}, () => item)
console.log('arr', arr)
https://stackoverflow.com/questions/51831998
复制相似问题