Error when specifying variable for index of empty double array using for loop - JavaScript

Asked 1 years ago, Updated 1 years ago, 109 views

testOne = [['ex','ex','ex'],['ex','ex','ex'],['ex','ex','ex'],['ex','ex','ex'],['ex','ex','ex'],];
xx = [];
realCal = ['a','b','c'];
    for (let i = 0; i < testOne.length; i++) 
          {
          xx[i] = realCal;
          xx[i][0] = i;
       }
console.log(xx);

Results I want:

(5) [Array(3), Array(3), Array(3), Array(3), Array(3)]
0:  [0, "b", c]
1:  [1, "b", c]
2:  [2, "b", c]
3:  [3, "b", c]
4:  [4, "b", c]

Actual Results:

(5) [Array(3), Array(3), Array(3), Array(3), Array(3)]
0:  [4, "b", "c"]
1:  [4, "b", "c"]
2:  [4, "b", "c"]
3:  [4, "b", "c"]
4:  [4, "b", "c"]

I've been thinking about a solution for a week, but I can't do it at all. I'd appreciate it if you let me know.

javascript for array index 2d-array

2022-09-20 18:07

2 Answers

xx[i] = realCal.slice();

Duplicate the array using slices and assign.


2022-09-20 18:07

The person above explained a very good solution, but the explanation of why is missing, so to explain it to you, it is not "call by value" but "call by reference".

for (let i = 0; i < testOne.length; i++) {
      xx[i] = realCal;
      xx[i][0] = i;
 }

xx[i] = realCal;

This is the code for the problem, where you don't "copy" the value to "xx[i]", you just hand over the address value for realCal. If you run "xx[i][0] = i" in this state, you will run "realCal[i][0] = i". Therefore, you can create a new array through "realCal.splice()" as shown above and get the results you want.


2022-09-20 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.