2016-03-01 80 views
0

我試圖創建和初始化AngularJS應用程序內的JavaScript一個二維數組如下:創建和初始化數組二維在javascript

$scope.invalidVote = []; 
for (var i = 0; i < $scope.arry1.length; i += 1) { 
    $scope.answersCount[i] = $scope.arry1[i].arry2.length; 

    for(var j = 0; j < $scope.arry1[i].arry2.length; j += 1) { 
     $scope.invalidVote[i][j] = false; 
    } 
} 

但它不工作,什麼是應該做的正確方法那?

+0

我認爲$ scope.arry1存在並且是一個數組? – JanS

回答

1

試試這個:

$scope.invalidVote = []; 
for (var i = 0; i < $scope.arry1.length; i++) { 
    $scope.answersCount[i] = $scope.arry1[i].arry2.length; 
    $scope.invalidVote[i] = []; 

    for(var j = 0; j < $scope.arry1[i].arry2.length; j++) { 
     $scope.invalidVote[i][j] = false; 
    } 
} 
+0

'$ scope.arry1 [i] .arry2.length'將不起作用。它應該讀取'$ scope.arry1 [1] .length' - 假定arry1是一個數組的數組,而不是一個數組,它的所有屬性都是數組arry2,這是一個數組 – JanS

+0

這是隻有原始海報才能回答的問題 – valepu

+0

您是對的。不過,它不會是二維數組。 – JanS

1

我假設$scope.arry1[i]是包含其他數組和已經與值填充數組。 所以,你的代碼應該是這樣的:

$scope.invalidVote = $scope.arry1; 
for (var i = 0; i < $scope.arry1.length; i += 1) 
    { 
    $scope.answersCount[i] = $scope.arry1[i].length; 
    for(var j = 0; j < $scope.arry1[i].length; j += 1) 
     { 
     $scope.invalidVote[i][j] = false; 
     } 
    } 

'$ scope.invalidVote = $ scope.arry1;'像這樣聲明「invalidVote」確保它包含相同數量的索引。