【发布时间】:2011-09-05 17:01:54
【问题描述】:
我在这样的变量中有 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,所以如果该库中有可用的东西,请告诉我。
【问题讨论】:
-
for (var piece in ...) piece 本身持有作品名称
-
德拉特。当我在回答之前发表评论时,我真的失去了代表:(
标签: javascript jquery json for-loop each