0

i created a Two-dimensional array and tried to change the value of an element in it like this:

    let testMap=new Array(3).fill(new Array(4).fill(0));
    console.log("begin",testMap);
    testMap[0][0]=1;
    console.log("end",testMap);

i thought the result would be testMap[0][0]=1 and others didn't change,but its result was(at Leetcode):

begin [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
end [ [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ] ]

what's more when it ran at my Vscode, its result was(using Chrome):

begin [ [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ] ]
end [ [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ], [ 1, 0, 0, 0 ] ]

Why is the entire column of elements modified and their results different?i wonder why it happened and it really made me puzzled.if i want to avoid it,which method is recommended?thanks

0 Answers0