假设我在"人类"中有几个嵌套对象(human1,human2,human3)。宾语。
human: {
"human1": {
"name" : "John",
"sex" : "male",
"age" : 18
}
"human2": {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
"human3": {
"name" : "May",
"sex" : "female",
"age" : 19
}
}
我在下面有另一个名为 currentPlayer 的对象,我希望它成为一个容器,以便从" human1"," human2&#访问数据34;,或者#34; human3"用于不同的用途。
currentPlayer: {
"name" : "default",
"sex" : "default",
"age" : 0
}
示例:今天我希望currentPlayer成为John,它就是
currentPlayer: {
"name" : "John",
"sex" : "male",
"age" : 18
}
然后我希望currentPlayer成为彼得,它就是:
currentPlayer: {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
如何使用循环迭代currentPlayer的属性值,而不仅仅是逐个键入?感谢...
答案 0 :(得分:1)
Bellow代码将遍历人类对象的所有属性
listofhuman = Object.getOwnPropertyNames(human);
var currentPlayer;
for (var objHumanName in listofhuman) {
if (listofhuman[objHumanName].Name === "Jonh") {
currentPlayer = Object.create(listofhuman[objHumanName]);
break;
}
}
在这个循环结束时,你会得到你想要的人
如果你执行Object.getOwnPropertyNames(currentPlayer)
,这将返回对象currentPlayer中实际键的字符串数组,您可以通过currentPlayer[arryofProp[0]]