javascript 嵌套循环中数组 2d 中的变量丢失

javascript variable in array 2d in nested loop is missing

我创建动态 table 然后存储值。但我发现最终数组是错误的。 我想有人帮助和扩大问题。为什么 x in x before loop = [[]] 而不是 [["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(); });

结果是

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"]]

我要的是final [["111", "0", "0"], ["222", "0", "0"]]

您一直将同一个数组推送到 xx.push(y) 不会复制数组,它只是推送对数组的引用。不要使用 y.length = 0 清空数组,而是使用 y = [].

分配一个新数组