【问题标题】:How to add same elements to javascript array n times如何将相同的元素添加到javascript数组n次
【发布时间】:2022-01-04 23:08:40
【问题描述】:
var fruits = [];
fruits.push("lemon", "lemon", "lemon", "lemon");

与其推送相同的元素,不如这样写一次:

fruits.push("lemon" * 4 times)

【问题讨论】:

标签: javascript arrays


【解决方案1】:

对于原语,使用.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);

【讨论】:

  • 当然,不要使用它错误。不幸的是,有很多方法可以使用很多错误的东西,new ArrayArray.from 都不是例外。 new Array 没问题,只要你之后填充数组。
【解决方案2】:

尝试使用数组构造函数:

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

在此处查看更多信息Array

【讨论】:

  • 数组不需要new
【解决方案3】:

You shouldn't use the array constructor, 改用[]

const myArray = [];   // declare array

myArray.length = 5; // set array size
myArray.fill('foo'); // fill array with any value

console.log(myArray); // log it to the console

【讨论】:

    【解决方案4】:
       const item = 'lemon'
       const arr = Array.from({length: 10}, () => item)
    

    const item = 'lemon'
    const arr = Array.from({length: 10}, () => item)
    console.log('arr', arr)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      相关资源
      最近更新 更多