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

查看:25
本文介绍了如何将相同的元素添加到 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,因为这样数组中的所有元素都会引用内存中的同一个对象,所以对数组中的一项的突变会影响到数组中的每一项数组.

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.

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 来完成:

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);

有关如何以这种方式创建二维数组的示例:

For an example of how to create a 2D array this way:

var fruits = Array.from(
  { length: 2 }, // outer array length
  () => Array.from(
    { length: 3 }, // inner array length
    () => ({ Lemon: 'Lemon' })
  )
);
console.log(fruits);

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

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