javascript - 如何在 JavaScript 中用 undefined 填充锯齿状的多维数组?

标签 javascript arrays matrix

我的目标是转置一个矩阵;然而,子数组的长度并不都相等。例如:[[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/

相关文章:

javascript - 在 react 类: How do I pass a variable inside same component中

javascript - 我如何以这样的方式设计一个对象,我可以像这样制定一个 JSON?

java - 如何将枚举转换为固定大小的 byte[]

python - 根据多个条件替换 numpy 数组中的值而不使用任何循环

r - 矩阵和表名/dimnames

r - R中矩阵的索引值?

javascript - 自定义推文给出 "32: Could not authenticate you."错误。知道为什么吗?

javascript - 无法从 Ajax getAllResponseHeaders 获取自定义 HTTP header 响应

c - 尝试将数组中的数据保存到文件中

python - Tensorflow 获取张量中值的索引