小编Hap*_*ppy的帖子

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

javascript each jquery json for-loop

5
推荐指数
2
解决办法
8056
查看次数

标签 统计

each ×1

for-loop ×1

javascript ×1

jquery ×1

json ×1