How do you easily create empty matrices javascript?

前端 未结 17 1292
[愿得一人]
[愿得一人] 2020-12-04 16:29

In python, you can do this:

[([None] * 9) for x in range(9)]

and you\'ll get this:

[[None, None, None, None, None, None, No         


        
相关标签:
17条回答
  • 2020-12-04 16:49

    Coffeescript to the rescue!

    [1..9].map -> [1..9].map -> null

    0 讨论(0)
  • 2020-12-04 16:49
    Array.from(new Array(row), () => new Array(col).fill(0));
    
    0 讨论(0)
  • 2020-12-04 16:55

    Use this function or some like that. :)

    function createMatrix(line, col, defaultValue = 0){ 
        return new Array(line).fill(defaultValue).map((x)=>{ return new Array(col).fill(defaultValue); return x; }); 
    }
    var myMatrix = createMatrix(9,9);
    
    0 讨论(0)
  • 2020-12-04 16:57

    The question is slightly ambiguous, since None can translate into either undefined or null. null is a better choice:

    var a = [], b;
    var i, j;
    for (i = 0; i < 9; i++) {
      for (j = 0, b = []; j < 9; j++) {
        b.push(null);
      }
      a.push(b);
    }
    

    If undefined, you can be sloppy and just don't bother, everything is undefined anyway. :)

    0 讨论(0)
  • 2020-12-04 16:58

    // initializing depending on i,j:
    var M=Array.from({length:9}, (_,i) => Array.from({length:9}, (_,j) => i+'x'+j))
    
    // Print it:
    
    console.table(M)
    // M.forEach(r => console.log(r))
    document.body.innerHTML = `<pre>${M.map(r => r.join('\t')).join('\n')}</pre>`
    // JSON.stringify(M, null, 2) // bad for matrices

    Beware that doing this below, is wrong:

    // var M=Array(9).fill([]) // since arrays are sparse
    // or Array(9).fill(Array(9).fill(0))// initialization
    
    // M[4][4] = 1
    // M[3][4] is now 1 too!
    

    Because it creates the same reference of Array 9 times, so modifying an item modifies also items at the same index of other rows (since it's the same reference), so you need an additional call to .slice or .map on the rows to copy them (cf torazaburo's answer which fell in this trap)

    note: It may look like this in the future, with slice-notation-literal proposal (stage 1)

    const M = [...1:10].map(i => [...1:10].map(j => i+'x'+j))
    
    0 讨论(0)
  • 2020-12-04 17:00

    There is something about Array.fill I need to mention.

    If you just use below method to create a 3x3 matrix.

    Array(3).fill(Array(3).fill(0));
    

    You will find that the values in the matrix is a reference.


    Optimized solution (prevent passing by reference):

    If you want to pass by value rather than reference, you can leverage Array.map to create it.

    Array(3).fill(null).map(() => Array(3).fill(0));
    

    0 讨论(0)
提交回复
热议问题