mercredi 15 décembre 2021

Js Math.random not random [duplicate]

I can't generate a multidimensional array and fill it with random values, I tried to use for loops, forEach, and map with Math.random, but all arrays are identical.

function mat(a=5,b=5,max=2){
  
  let mt = new Array(a).fill(
    new Array(b).fill(0)
  )
  
  mt.map( (x,xk)=>{ 
    x.map( (y,yk)=>{ 
      mt[xk][yk] = Math.round(
        Math.random()*max
      )
    })
  })
  
  return mt
}
console.log(JSON.stringify(mat()))

output example

[[0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0],
 [0,0,2,2,0]]

why?? does not make sense!




Aucun commentaire:

Enregistrer un commentaire