您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

var fruits = Array.from(

  { length: 2 }, // outer array length

  () => Array.from(

    { length: 3 }, // inner array length

    () => ({ Lemon: 'Lemon' })

  )

);

console.log(fruits);
javascript 2022/1/1 18:21:56 有415人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶