我想创建一个像这样的数组矩阵:
createMatrix(4);
// logs:
[[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]];
目前我的解决方案是:
function createMatrix (n) {
var innerArr;
var outerArr = [];
for (var i=0; i<n; i++){
innerArr = [];
for (var j=0; j<n; j++) {
innerArr.push(0);
}
outerArr.push(innerArr);
}
}
console.log(outerArr);
有没有更有效的方法来做到这一点?这将迭代 nxn 次,这对于非常简单的事情来说效率非常低。
最佳答案
使用 ECMAScript 2015 函数 Array.prototype.fill()
:
Array(row_count).fill(Array(column_count).fill(0)).map(a => a.slice())
说明:
// a sparse array with row_count "absent" items:
Array(row_count)
// an array with column_count members with the value 0:
Array(column_count).fill(0)
// an array with row_count times the identic array as value:
Array(row_count).fill(Array(column_count).fill(0))
// shallow copy the inner array:
Array(row_count).fill(Array(column_count).fill(0)).map(a => a.slice())
速度?
- n=4: http://jsperf.com/creatematrix/1
- n=8:http://jsperf.com/creatematrix/2 n=16:http://jsperf.com/creatematrix/3
- n=32:http://jsperf.com/creatematrix/4
表面上,随着矩阵的增长(相对于循环),Array.prototype.fill() 变体变得更快。 至少在 Firefox 中是这样。 YMMV。
关于javascript - 如何创建一个全为零的 nxn 矩阵(数组的数组)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34055488/