如何在 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
}
如何从中获取当前片段名称?例如,我们当前位于第一个元素(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"
}
我也在我的项目中使用 jQuery,所以如果该库中有可用的东西,请告诉我。
I have JSON object inside variable like this:
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"
},...
};
And I'm iterating trough them with for each loop:
for (var piece in chessPieces){
//some code
}
How would I get current pieces name from this? For example, we are currently on the first element(piece = 0): chessPiece[piece].GiveMeTheName
==> which results in string "p-w-1".
I actually intend to pass the current element into the function, cos I need to check something, so it would look something like this:
//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"
}
I'm also using jQuery in my project, so if there's something usable in that library, let me know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 $.each(obj, fn)。该函数允许访问当前元素的对象键。
I'd use $.each(obj, fn). The function allows access to the object key of the current element.
嗯。
piece
不是已经是对象的名称了吗? JavaScript 中的for ... in
为您提供键名。因此,当您执行
for (varpiece in chessPieces) console.log(piece);
时,它将打印出pw-1
,pw-2
等Erm. Isn't
piece
already the name of the object? Thefor ... in
in JavaScript gives you the key name.So when you do
for (var piece in chessPieces) console.log(piece);
, it will print outp-w-1
,p-w-2
etc