Javascript循环错误:未捕获的TypeError

时间:2017-01-15 16:44:34

标签: javascript arrays multidimensional-array

我正在练习Javascript并使用以下代码在Uncaught TypeError: Cannot set property '0' of undefined行返回sets[i][j] = initial_sets [i][j];错误。这个想法似乎是正确的,但我无法弄清楚为什么我会收到错误。

var sets = [[],[]]; //Declared this 2D array based on solution in https://stackoverflow.com/questions/16512182/how-to-create-empty-2d-array-in-javascript
var initial_sets=[[a,b],[c,d],[e,f]]; //2D array
var i,j;

//2D array sets is being filled by 2D array initial_sets
for (i=0; i<initial_sets.length; i++) {
    for (j=0; j<initial_sets[i].length; j++) {
            sets[i][j] = initial_sets[i][j];
    }
}

我通过创建一维数组然后为其分配了另一个维度来尝试在Uncaught TypeError: Cannot set property '0' of undefined "中发布的解决方案,但我仍然得到相同的错误。

3 个答案:

答案 0 :(得分:1)

var sets = [];
var initial_sets=[[a,b],[c,d],[e,f]];
var i,j;

for (i=0; i<initial_sets.length; i++) {
    // check if sets[i] exist. if not push a new emty array to it.
    if(!sets[i]) sets.push([]);
    for (j=0; j<initial_sets[i].length; j++) {
            sets[i][j] = initial_sets[i][j];
    }
}

然后你不必用空数组初始化sets,它会在需要时推送它们。

答案 1 :(得分:0)

阵列的尺寸不一样。

var sets = []; 
var initial_sets=[["a","b"],["c","d"],["e","f"]];
var i,j;

for (i=0; i<initial_sets.length; i++) { 
    var tmp = [];
    for (j=0; j<initial_sets[i].length; j++) {
            tmp[j] = initial_sets[i][j];
    }
    sets[i] = tmp;
}

OR

var sets = []; 
var initial_sets=[["a","b"],["c","d"],["e","f"]];
var i,j;

for (i=0; i<initial_sets.length; i++) { 
    sets[i] = []; 
    for (j=0; j<initial_sets[i].length; j++) {
            sets[i][j] = initial_sets[i][j];
    }    
}

答案 2 :(得分:0)

试试这个:

var sets = [];
var initial_sets=[['a','b'],['c','d'],['e','f']];
var i,j;

for (i=0; i<initial_sets.length; i++){ 
  sets[i]=[];
  for (j=0; j<initial_sets[i].length; j++){
    sets[i].push(initial_sets[i][j]);
  }
}
console.log(sets);