假设我在“人”对象中有几个嵌套对象(人1,人2,人3)。
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”或“ human3”访问数据以用于不同用途。
currentPlayer: {
"name" : "default",
"sex" : "default",
"age" : 0
}
示例:今天我希望currentPlayer成为John,然后
currentPlayer: {
"name" : "John",
"sex" : "male",
"age" : 18
}
然后,我希望currentPlayer成为Peter,然后它就会:
currentPlayer: {
"name" : "Peter",
"sex" : "male",
"age" : 16
}
我该如何使用循环迭代currentPlayer的属性值,而不仅是逐一键入?谢谢...
最佳答案
波纹管代码将遍历人类对象的所有属性
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]]
访问这些值