如何将相同的元素添加到javascript数组n次 [英] How to add same elements to javascript array n times

查看:119
本文介绍了如何将相同的元素添加到javascript数组n次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");

除了推送相同的元素之外,如何写一次:

Instead of pushing same elements how can write it once like this:

fruits.push("lemon" * 4 times)


推荐答案

对于基元,请使用 .fill

var fruits = new Array(4).fill('Lemon');
console.log(fruits);

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

For non-primitives, don't use fill, because then all elements in the array will reference the same object in memory, so mutations to one item in the array will affect every item in the array - instead, explicitly create the object on each iteration, which can be done with Array.from:

var fruits = Array.from(
  { length: 4 },
  () => ({ Lemon: 'Lemon' })
);
console.log(fruits);

这篇关于如何将相同的元素添加到javascript数组n次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆