我有一个变量里面包含了如下的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 each循环迭代它们:
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,如果这个库中有可用的内容,请告诉我。