我在变量里面有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"
},...
};
Run Code Online (Sandbox Code Playgroud)
我正在为每个循环迭代它们:
for (var piece in chessPieces){
//some code
}
Run Code Online (Sandbox Code Playgroud)
我如何从中获取当前的名称?例如,我们当前在第一个元素(piece = 0):chessPiece[piece].GiveMeTheName==>,这导致字符串"pw-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"
}
Run Code Online (Sandbox Code Playgroud)
我也在我的项目中使用jQuery,所以如果该库中有可用的东西,请告诉我.