【问题标题】:How to get name of current JSON property while iterating through them in JavaScript?如何在 JavaScript 中迭代它们时获取当前 JSON 属性的名称?
【发布时间】:2011-09-05 17:01:54
【问题描述】:

我在这样的变量中有 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
}

我如何从中获得当前作品的名称?例如,我们当前在第一个元素(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 本身持有作品名称
  • 德拉特。当我在回答之前发表评论时,我真的失去了代表:(

标签: javascript jquery json for-loop each


【解决方案1】:
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] 时给了我未定义的信息
    • chessPieces,假设是一个哈希表,在JavaScript中也是一个对象。索引为 1 似乎.. un-js-objecty。
    【解决方案3】:

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

    $.each(chessPieces, function(key, value) {
    
       //key = "p-w-1"
       //value = { "role":"pawn", ... }
       //this === value
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多