最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: Faster way to create and initialize two dimensional array (matrix) - Stack Overflow

programmeradmin3浏览0评论

Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:

var nodes = new Array(ast.length);

for (var i=0; i < nodes.length; i++){
    nodes[i] = new Array(ast.length);
    for (var j=0; j < nodes.length; j++)
        nodes[i][j]=0;
}

Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:

var nodes = new Array(ast.length);

for (var i=0; i < nodes.length; i++){
    nodes[i] = new Array(ast.length);
    for (var j=0; j < nodes.length; j++)
        nodes[i][j]=0;
}
Share Improve this question asked Jan 13, 2016 at 18:01 SaadSaad 1,3604 gold badges27 silver badges42 bronze badges 1
  • Duplicate of - stackoverflow./q/6495187/104380 – vsync Commented Mar 26, 2016 at 16:57
Add a ment  | 

4 Answers 4

Reset to default 5

You could use the Array.prototype.fill method:

var nodes = Array(ast.length).fill(Array(ast.length).fill(0));

jsperf test: http://jsperf./fill-array-matrix

Since you asked for "faster", it looks like you can gain some speed by creating a single initalized array and then using .slice() to copy it rather than initializing each array itself:

var nodes = new Array(ast.length);
var copy = new Array(ast.length);
for (var i = 0; i < ast.length; i++) {
    copy[i] = 0;
}

for (var i=0; i < nodes.length; i++){
    nodes[i] = copy.slice(0);
}

jsperf test: http://jsperf./slice-vs-for-two-d-array/2

This method looks to be 10-20% faster in all three major browsers.

You can create array of zeros once and create copies of it:

var length = 10;

var zeros = Array.apply(null, Array(length)).map(Number.prototype.valueOf, 0);
var nodes = zeros.map(function(i) {
    return zeros.slice();
});

console.log(nodes);

I don't know how fast this is in terms of producing a 2d array but it is IMHO a better way that most.

Array.prototype.dim = function(){
    if( this.length==2 ){
        r=this.shift(); c=this.shift();
        while( r-- ) this.push( new Array( c ).fill(0,0) );
        return this;
    }
}

In use, the 2d array is made by initialising a regular 1d array with the parameters of x,y or rows, cols as two parameters. These are then used to dimension the array and fill it with zeros at the same time.

var arr = new Array(5,7).dim();
console.log(arr[4]);

The array then has got the desired dimension with zeros.

The output:

console.log(arr[4]);
 (7) [0, 0, 0, 0, 0, 0, 0]

I hope someone finds this useful.

发布评论

评论列表(0)

  1. 暂无评论