在JavaScript中迭代时如何获取当前JSON属性的名称?
|
我有这样的变量内的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
}
我将如何从中获得当前的作品名称?例如,我们当前在第一个元素上(件= 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,所以如果该库中有可用的东西,请告诉我。
没有找到相关结果
已邀请:
3 个回复
焙恍挝厂熄
已经不是对象的名称了吗? JavaScript中的“ 5”为您提供密钥名称。 因此,当您执行
时,它将打印出
,
等
孝铜差
辽躺