如何在javascript中正确初始化二维数组?

时间:2016-04-04 20:18:07

标签: javascript arrays

根据this问题提出的建议我正在尝试创建一个二维数组,但是我正在运行时遇到错误我认为这是因为格式化不正确或我遗漏了一些事先初始化。

Uncaught TypeError: Cannot set property '1' of undefined

以下是我的代码目前的示例:

var answers = [];
answers [0] = [];
answers[0][1] = accept; answers[0][2] = wrong; answers[0][3] = wrong; 
answers[1][1] = wrong; answers[1][2] = best; answers[1][3] = wrong; 

3 个答案:

答案 0 :(得分:4)

您缺少初始化,您从未初始化array[1]

以下是使用此修补程序的代码版本:

var answers = [];
answers[0] = [];
answers[1] = [];
answers[0][1] = accept;
answers[0][2] = wrong;
answers[0][3] = wrong; 
answers[1][1] = wrong;
answers[1][2] = best;
answers[1][3] = wrong;

答案 1 :(得分:2)

如果你对这些元素进行硬编码,你可以这样做:

var answers = [
    [accept, wrong, wrong],
    [wrong, best, wrong]
];

假设acceptwrongbest是vars。

答案 2 :(得分:1)

如果你不想打扰数组是否已经初始化,你可以初始化它,如果它没有被定义,如下所示:

function insert(array,path,value) {
  path.forEach(function(i,pos) {
    if(array[i]===undefined) array[i] = [];
    if(pos<path.length-1) array = array[i];
    else array[i] = value;
  });
}

var answers = [];
insert(answers,[1,2,3],"accept");
alert(answers[1][2][3]); // accept