2016-11-02 84 views
2

我正在獲取屬性值。我需要設置爲多維數組,但它顯示錯誤。即時發生錯誤?設置jquery多維數組

var myArray = []; 
amount=10; 
x=1 
$(id).closest('td').nextAll().find('input').each(function (n) { 

     myArray[x]['id'] = $(this).attr('data-id'); 
     myArray[x]['year'] = $(this).attr('data-year'); 
     myArray[x]['month'] = $(this).attr('data-month'); 
     myArray[x]['amount'] = amount; 

     x++; 
}); 
console.log(myArray); 
+1

的[創建通過它二維數組和循環可能的複製在jquery](http://stackoverflow.com/questions/26140640/create-two-dimensional-array-and-loop-through-it-in-jquery) –

回答

1

你缺少這一行

myArray[x] = {}; 

此行

myArray[x]['id'] = $(this).attr('data-id'); 

之前,因爲你需要初始化這個對象屬性設置爲前第一。

0

數組需要首先聲明才能添加項目。例如

var d = []; 
var value = 2; 
d[0]["key"] = value; 

將不起作用,因爲d[0]還不是數組。但是:

var d = []; 
var value = 2; 
d[0]= []; 
d[0]["key"] = value; 

會工作,因爲d[0]已準備好接受密鑰。

在你的情況;

>>> myArray[x] = []; 
myArray[x]['id'] = $(this).attr('data-id'); 
myArray[x]['year'] = $(this).attr('data-year'); 
myArray[x]['month'] = $(this).attr('data-month'); 
myArray[x]['amount'] = amount; 

將工作。

0

儘管您已經將數組初始化爲空數組,但您應該初始化該數組的位置。當你不指定時,myArray [x]是未定義的。所以,你需要明確指定一個空的對象,從而使用更新的密鑰myarray的[X] [「鑰匙」]

var myArray = []; 
 
amount = 10; 
 
x = 1 
 
$(id).closest('td').nextAll().find('input').each(function(n) { 
 
    //Need to initialize with an object a location x; 
 
    myArray[x] = {}; 
 
    myArray[x]['id'] = $(this).attr('data-id'); 
 
    myArray[x]['year'] = $(this).attr('data-year'); 
 
    myArray[x]['month'] = $(this).attr('data-month'); 
 
    myArray[x]['amount'] = amount; 
 

 
    x++; 
 
}); 
 
console.log(myArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>