如何在JavaScript中遍历JSON属性时获取当前属性的名称?

5

我有一个变量里面包含了如下的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 each循环迭代它们:
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,如果这个库中有可用的内容,请告诉我。


for (var piece in ...)中的piece本身就保存了棋子的名称。 - mplungjan
糟糕,当我在回答之前评论时,我的声望真的会下降 :( - mplungjan
3个回答

7
我会使用$.each(obj, fn)。该函数允许访问当前元素的对象键。
$.each(chessPieces, function(key, value) {

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

});

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

2

额,piece不是对象的名称吗?在JavaScript中的for ... in语句会返回键名。

因此,当您执行for (var piece in chessPieces) console.log(piece);时,它将打印出p-w-1p-w-2等。


谢谢,我感到困惑,因为在 Chrome 控制台中键入 chessPieces[1] 时出现了 undefined。 - Happy
1
它是 chessPieces,应该是一个哈希表,在 JavaScript 中也是一个对象。索引为1似乎不太像JavaScript对象。 - Pwnna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接