Search code examples
javascriptarraysmultidimensional-arraynested-loops

javascript variable in array 2d in nested loop is missing


I create dynamic table then store value. But I found final array is mistake. I want to somebody help and expand problem. Why x in x before loop = [[]] not [["111", "0", "0"]].

x = [];
$(document).on('click', '#save', function(event) {
    x.length = 0;
    var y = [];
    for (var m = 0; m < row; m++) {
      y.length = 0;
      console.log('x before loop = ',x);
      for (var n = 0; n < arr_stklist.length - 1; n++) {
        if (arr_stklist[n] == "text") {
          y.push(document.getElementById('arr_TextAns['+m+']['+n+']').value);
        } else if (arr_stklist[n] == "level") {
          y.push(document.getElementById('arr_LevelAns['+m+']['+n+']').value);
        } 
      }
      // console.log('y = ',y);
      // console.log('x before = ',x);
      x.push(y);
      // console.log('x after = ',x);
    }
    // console.log('final = ',x);
    event.preventDefault(); });

result is

x before loop = []
y = ["111", "0", "0"]
x before = []
x after = [["111", "0", "0"]]
x before loop = [[]]
y = ["222", "0", "0"]
x before = [["222", "0", "0"]]
x after = [["222", "0", "0"], ["222", "0", "0"]]
final = [["222", "0", "0"], ["222", "0", "0"]]

I want final is [["111", "0", "0"], ["222", "0", "0"]]


Solution

  • You keep pushing the same array onto x. x.push(y) doesn't make a copy of the array, it just pushes a reference to the array. Instead of emptying the array with y.length = 0, assign a new array with y = [].