gpt4 book ai didi

Javascript,将字符串转换为对象属性

转载 作者:行者123 更新时间:2023-12-03 12:08:22 25 4
gpt4 key购买 nike

我想知道是否可以有一个具有某些属性的对象,例如:

对象名称:人类

this.age = 8
this.name = "Steve"

然后有一个字符串数组,其中包含该对象的每个属性,例如:

manAttributes = ["age","name"]

因此,如果我写

console.log(Human.manAttributes[0])

控制台应该记录“8”,但这不起作用,我得到了意外的字符串。

谢谢

最佳答案

对象是一个键:值对。键和值由 :(冒号)分隔。就您而言,您已用 = 分隔。更改您的代码如下:

 var Human = {
manAttributes: ["age","name"],
age: 8
};
alert(Human[Human.manAttributes[0]]); //alerts 8

此解决方案将 manAttributes 视为 Human 对象的属性。如果 manAttributes 是 Human 对象之外的单独数组,那么,

 var manAttributes = ["age","name"];
var Human = {
age: 8
};
alert(Human[manAttributes[0]]); //alerts 8

关于Javascript,将字符串转换为对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25077355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com