0

I'm trying to fill a 2D Array initialized :

var cropField = 
new Array(Math.floor((Math.random() * 9) + 1)).fill(new Array(Math.floor(Math.random() * 9) + 1).fill(" "));

Then, I traverse through the Array:

for (var i = 0; i < cropField.length; i++) {
    row = cropField[i];
    for (var j = 0; j < row.length; j++) {
        cropField[i][j] = Math.random() > 0.5 ? "A" : "B";
    }
}

I'm trying to fill the array with either A or B, randomly. But then this happens:

[ [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ],
  [ 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'B' ] ]

They appear in columns.

I've tried using a forEach loop, that does the same thing.

Anyway I can get random values?

  • Use `Array.from` instead of `.fill` for non-primitives – CertainPerformance Feb 22 '20 at 12:09
  • 1
    To clarify, by using `.fill`, you've set each row of the grid to be the *same array*. Thus, a modification to any of the rows will affect all the rows. You need to make each row an independent copy, either by using `Array.from` or by other means. [Take a look at this question to understand the underlying cause here.](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – CRice Feb 22 '20 at 12:14
  • 1
    @bhoodream The odd behavior OP is experiencing is *because* he's using `.fill`. Whether he wants to create a 2d array of random values, or a 2d array of other objects, the essence is the same - don't use `.fill` with non-primitives unless you want every item in the array to be a reference to the same object – CertainPerformance Feb 22 '20 at 12:17
  • @CertainPerformance I saw your answer on the linked post, and I'll be doing it that way. Thanks for letting me know : using .fill() makes all elements point to a single value? –  Feb 22 '20 at 12:20
  • Yeah, another way to think of it is: when you use `.fill`, it's like `const arrayItem = ; for (let i = 0; i < arr.length; i++) arr[i] = arrayItem` Same object – CertainPerformance Feb 22 '20 at 12:21

0 Answers0