在不同的数据选项之间循环迭代对象
Iterate object with loop between different data options
假设我在 "human" 对象中有几个嵌套对象(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"、[=28= 访问数据],或 "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)
这将 return 字符串数组,它们是对象 currentPlayer 中的实际键,你可以通过 currentPlayer[arryofProp[0]]
访问这些值
假设我在 "human" 对象中有几个嵌套对象(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"、[=28= 访问数据],或 "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)
这将 return 字符串数组,它们是对象 currentPlayer 中的实际键,你可以通过 currentPlayer[arryofProp[0]]