0

All I'm trying to do here is generate an empty "field" or two dimensional array with a start position and a specified width and height.

it should look like this:

[
  ['*','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
  ['░','░','░','░','░','░','░','░','░','░'],
]

But for some reason my function prints this:

[
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
  ['*','░','░','░','░','░','░','░','░','░'],
]

This is really strange since I'm using arr[0][0] = '*' to add the start point.

Here is my code:

function generateField(width, height) {
  let newField = [];
  let row = '░'.repeat(width).split('');

  for (let i = 0; i < height; i++) {
    newField.push(row);
  }

  console.log(newField);
  newField[0][0] = '*'; // problem here
  console.log(newField);

  return newField;
}

const myField = generateField(10, 10);

I'm not really sure why this is happening or how to fix it, so any help would be appreciated.

furgus
  • 1
  • 2
  • You are only creating one row and insert it multiple times – Sebastian Speitel Feb 05 '22 at 14:53
  • `.split` returns a new array. You’ve created only one new array. `const row = "░".repeat(width);` and `newField.push(row.split(""));` would create several new arrays. Please be aware that [`split` is not a good way to separate strings into characters](/q/35223206/4642212). Much better would be: `const generateField = (width, height) => { const newField = Array.from({ length: height }, () => Array.from("░".repeat(width))); newField[0][0] = "*"; return newField; };` – Sebastian Simon Feb 05 '22 at 14:55

0 Answers0