2011-05-31 77 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) 
}