我刚刚学习 javascript。我对操作多维数组感到非常困惑。
var myarr = [
[ 7, 9, 10 ],
[ 6, 9 ],
[ 5, 9 ]
]
我想像这样插入零。在 javascript 中执行此操作的明智方法是什么
[
[ 7, 9, 10 ],
[ 6, 9, 0 ],
[ 5, 9, 0 ]
]
最佳答案
您可以首先获取内部数组的最大长度并插入零,直到所有内部数组具有相同的长度。
var myarr = [[7, 9, 10], [6, 9], [5, 9]],
length = myarr.reduce(function (r, a) { return Math.max(r, a.length); }, 0);
myarr.forEach(function (a) {
while (a.length < length) {
a.push(0);
};
});
console.log(myarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何在javascript中将零填充到我的多维数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40086423/