在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,所以如果该库中有可用的东西,请告诉我。     
已邀请:
        恩
piece
已经不是对象的名称了吗? JavaScript中的“ 5”为您提供密钥名称。 因此,当您执行
for (var piece in chessPieces) console.log(piece);
时,它将打印出
p-w-1
p-w-2
等     
        我会使用$ .each(obj,fn)。该功能允许访问当前元素的对象键。
$.each(chessPieces, function(key, value) {

   //key = \"p-w-1\"
   //value = { \"role\":\"pawn\", ... }
   //this === value

});
    
        
for (var piece in chessPieces){
    alert(piece)
}
    

要回复问题请先登录注册