缺少嵌套循环中数组2d中的javascript变量

时间:2015-02-22 12:16:29

标签: javascript arrays multidimensional-array nested-loops

我创建动态表然后存储值。但我发现最终阵列是错误的。 我希望有人帮助并扩大问题。为什么x之前的x = [[]]而不是[[" 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"]]

1 个答案:

答案 0 :(得分:0)

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