首页 > 解决方案 > 如何在二维数组中使用 Array.push 推送单个值?

问题描述

const y = [...Array(2)].map(() => Array(3).fill([]));
console.log('Before: ', JSON.stringify(y)); 
// Before:  [[[],[],[]],[[],[],[]]]
y[0][1].push("foo");
console.log('After: ', JSON.stringify(y)); 
// After:  [[["foo"],["foo"],["foo"]],[[],[],[]]]

为什么“foo”被插入了三遍?我怎样才能只在第一个中插入“foo”,即我怎样才能得到

// After:  [[["foo"],[],[]],[[],[],[]]]

标签: javascript

解决方案


推荐阅读