首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将相同的元素添加到javascript数组n次

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

Stack Overflow用户
提问于 2018-08-14 07:55:08
回答 3查看 6.7K关注 0票数 17
var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");

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

fruits.push("lemon" * 4 times)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 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);

票数 37
EN

Stack Overflow用户

发布于 2018-08-14 08:00:23

尝试使用Array构造函数:

let myArray = Array(times).fill(elemnt)

请在此处查看更多信息Array

票数 3
EN

Stack Overflow用户

发布于 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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51831998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档