[英]JavaScript Two dimensional Array
我正在創建javascript二維數組
代碼是:
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
輸出為:
[undefined,[]左140 paId“ 1”前10名
它有什么問題任何幫助都應得到幫助。
問題出在數組的顯示方法中。 該信息在那里,但是alert
和console.log
都不會顯示給您,因為期望數組唯一有趣的屬性是帶有數字索引的屬性。
在JavaScript中,與PHP不同,對象被用作地圖/關聯數組。
首先檢查您的信息是否確實存在:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
現在,使顯示方法起作用,您可以采用多種方法,但是最好的方法是使用對象:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
遍歷對象的屬性非常容易:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
添加hasOwnProperty
檢查是否您的對象不是從null繼承的( var obj = {}
需要它,這與var obj = Object.create(null)
)
您正在使用鍵字符串存儲值,而這是錯誤的,因為您將field_arr
聲明為數值數組(我認為JavaScript中沒有關聯數組之類的東西)。
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
您需要創建一個對象來存儲值,就像它們與字符串鍵相關聯一樣。 但從字面上看,它們是對象屬性
像這樣重新聲明
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
編輯:但是為了符合您當前的代碼,您可以通過像對象的屬性一樣訪問它來使用字符串訪問索引。 (感謝Tibos )
var field_arr=[];
...
...
field_arr[Id].paId = paId;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.