2011-05-31 48 views
5

我有內部變量JSON對象是這樣的:如何在JavaScript中迭代當前JSON屬性的名稱?

var chessPieces = { 
    "p-w-1" : { 
     "role":"pawn", 
     "position":{"x":1, "y":2}, 
     "state":"free", 
     "virgin":"yes" 
    }, 
    "p-w-2" : { 
     "role":"pawn", 
     "position":{"x":2, "y":2}, 
     "state":"free", 
     "virgin":"yes" 
    },... 
}; 

而且我迭代配線槽他們每個循環:

for (var piece in chessPieces){ 
    //some code 
} 

我怎麼會從這個獲取當前塊的名字嗎?例如,我們當前位於第一個元素(piece = 0):chessPiece[piece].GiveMeTheName ==>這導致字符串「p-w-1」。

其實我打算當前元素傳遞到功能,因爲我需要檢查什麼的,所以它看起來是這樣的:

//constructor for this function looks like this: function setPiece(piece,x,y); 
function setPiece(chessPiece[piece],chessPiece[piece].position.x,chessPiece[piece].position.y){ 
    //and here I need to get something like 
    piece.GiveMeTheName ==> which gives me string "p-w-1" 
} 

我也在我的項目中使用jQuery,所以如果那個圖書館有些東西可用,請告訴我。

在此先感謝! :)

+0

的片(在... VAR件)本身擁有一塊名 – mplungjan 2011-05-31 18:18:09

+0

討厭鬼。我在評論前真的失去了代表,我回答:( – mplungjan 2011-05-31 19:04:49

回答

2

Erm。是不是piece已經是對象的名稱? JavaScript中的for ... in爲您提供了關鍵名稱。

所以當你做for (var piece in chessPieces) console.log(piece);,它會打印出p-w-1p-w-2

+0

謝謝,我感到困惑,因爲鉻控制檯給我不明確的時候輸入'國際象棋[1]' – Happy 2011-05-31 18:24:00

+1

它是'國際象棋',它假設是一個哈希表,它是也是JavaScript中的一個對象,索引爲1似乎...... un-js-objecty。 – Pwnna 2011-05-31 18:25:52

7

我會用$.each(obj, fn)。該功能允許訪問當前元素的對象鍵。

$.each(chessPieces, function(key, value) { 

    //key = "p-w-1" 
    //value = { "role":"pawn", ... } 
    //this === value 

}); 
4
for (var piece in chessPieces){ 
    alert(piece) 
} 
相關問題