How do you easily create empty matrices javascript?

前端 未结 17 1440
[愿得一人]
[愿得一人] 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: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 = `
    ${M.map(r => r.join('\t')).join('\n')}
    ` // 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))
    

提交回复
热议问题