Confused from array fill results | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 12

Confused from array fill results

Can someone explain or tell me why the output Of this code: let input = "3x7"; let [rows, cols] = input.split(/x/i).map(v=>parseInt(v)) let matrix = new Array(rows).fill(new Array(cols).fill(0)) matrix[0][0] = 2 console.log(matrix) Is: [ [ 2, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, 0, 0, 0, 0 ], [ 2, 0, 0, 0, 0, 0, 0 ] ]

17th Feb 2019, 12:46 PM
Ahlin Chan
Ahlin Chan - avatar
1 Answer
+ 2
matrix[0], matrix[1] and matrix[2] are pointing to the same array (new Array(cols). fill(0l), thus it would be the same values for matrix[0][1], matrix[0][2] and matrix[0][2]
17th Feb 2019, 1:33 PM
Calviղ
Calviղ - avatar