如何在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,...
};

我正在为每个循环迭代它们:

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,所以如果该库中有可用的东西,请告诉我.

最佳答案
呃.是不是已经是对象的名称? JavaScript中的for … in为您提供了密钥名称.

因此,当你为(棋盘中的var件)console.log(piece);执行时,它将打印出p-w-1,p-w-2等

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...