I'm trying to create a nxn chessboard in single line of code using Array.fill like
let board = new Array(n).fill(new Array(n).fill('O'));
when i try to modify the first square like board[0][0] = 'Q'.It's changing all the 0th index elements all n sub arrays. My intention is
┌─────────┬─────┬─────┬─────┬─────┐
│ (index) │ 0 │ 1 │ 2 │ 3 │
├─────────┼─────┼─────┼─────┼─────┤
│ 0 │ 'Q' │ 'O' │ 'O' │ 'O' │
│ 1 │ 'O' │ 'O' │ 'O' │ 'O' │
│ 2 │ 'O' │ 'O' │ 'O' │ 'O' │
│ 3 │ 'O' │ 'O' │ 'O' │ 'O' │
└─────────┴─────┴─────┴─────┴─────┘
But when i do board[0][0] = 'Q'
┌─────────┬─────┬─────┬─────┬─────┐
│ (index) │ 0 │ 1 │ 2 │ 3 │
├─────────┼─────┼─────┼─────┼─────┤
│ 0 │ 'Q' │ 'O' │ 'O' │ 'O' │
│ 1 │ 'Q' │ 'O' │ 'O' │ 'O' │
│ 2 │ 'Q' │ 'O' │ 'O' │ 'O' │
│ 3 │ 'Q' │ 'O' │ 'O' │ 'O' │
└─────────┴─────┴─────┴─────┴─────┘
But it works as expected, when i'm creating array like this
let board = [
['O','O','O','O'],
['O','O','O','O'],
['O','O','O','O'],
['O','O','O','O'],
]