我的目标是转置一个矩阵;然而,子数组的长度并不都相等。例如:[[1,2,3], [4,5], [0,-1,0,0]]
。我无法转置它,因为索引不匹配。我需要的是:
[[1,2,3,undefined],
[4,5,undefined,undefined],
[0,-1,0,0]]
因此较短的行都与最长的行匹配相同的长度,但随后在扩展槽中填充了 undefined
。
我很清楚我可以通过可能被认为更慢或更粗糙的方式来做到这一点,即通过初始化和清空数组以及复制或连接 undefined
的数组。 javascript 是否有某种 native 方式来执行此操作?我看了一下 fill ,但这似乎不是我需要的。
最佳答案
尝试使用数组的length
属性,
var arr = [[1,2,3], [4,5], [0,-1,0,0]];
//getting the max length among the sub arrays.
var max = arr.reduce(function(a,b){ return Math.max(a, b.length) }, 0);
//setting the max length to all the sub arrays.
arr = arr.map(function(itm){ return (itm.length = max, itm) });
console.log(arr[0]); //[1, 2, 3, undefined × 1]
console.log(arr[1]); //[4, 5, undefined × 2]
console.log(arr[2]); //[0, -1, 0, 0]
好的,这是上面代码的普通版本,
var arr = [
[1, 2, 3],
[4, 5],
[0, -1, 0, 0]
];
//getting the max length among the sub arrays.
var max = arr.reduce(function(a, b) {
return Math.max(a, b.length)
}, 0);
//setting the max length to all the sub arrays.
arr = arr.map(function(itm) {
itm.length = max;
return itm
});
console.log(arr[0]); //[1, 2, 3, undefined × 1]
console.log(arr[1]); //[4, 5, undefined × 2]
console.log(arr[2]); //[0, -1, 0, 0]
这里有一个普通的 for 循环方法,可以让你清楚地理解,
var arr = [[1, 2, 3],[4, 5],[0, -1, 0, 0]];
var max = 0;
for(var i=0;i<arr.length;i++) {
max = Math.max(max, arr[i].length);
}
for(var i=0;i<arr.length;i++) {
arr[i].length = max
}
console.log(arr[0]); //[1, 2, 3, undefined × 1]
console.log(arr[1]); //[4, 5, undefined × 2]
console.log(arr[2]); //[0, -1, 0, 0]
DEMO
关于javascript - 如何在 JavaScript 中用 undefined 填充锯齿状的多维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361919/