Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript,将字符串转换为对象属性_Javascript_Object_Attributes - Fatal编程技术网

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

Javascript,将字符串转换为对象属性,javascript,object,attributes,Javascript,Object,Attributes,我想知道是否可能有一个具有某些属性的对象,例如: 对象名称:人类 然后有一个字符串数组,其中包含该对象的每个属性,例如: manAttributes = ["age","name"] 所以如果我写 console.log(Human.manAttributes[0]) 控制台应该记录“8”,但这不起作用,我得到了意外的字符串 如果您希望遍历这些属性,请向表示感谢, 我建议采取以下办法 var human = { name: "Smith", age: "29"

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

对象名称:人类

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

manAttributes = ["age","name"]
所以如果我写

console.log(Human.manAttributes[0])
控制台应该记录“8”,但这不起作用,我得到了意外的字符串


如果您希望遍历这些属性,请向

表示感谢, 我建议采取以下办法

var human = {      
  name: "Smith",
  age: "29"      
};

var manAttributes = ["age","name"];

for(var prop in manAttributes){
  if(human.hasOwnProperty(manAttributes[prop])){
    console.log(human[manAttributes[prop]]);
  }  
} 

对象是一对键:值。键和值由一个(冒号)分隔。在您的情况下,您用=分隔。按以下方式更改代码:

 var Human = {
     manAttributes: ["age","name"],
     age: 8
 };
 alert(Human[Human.manAttributes[0]]);  //alerts 8
此解决方案将ManAttribute视为人类对象的属性。如果manAttributes是人类对象之外的单独数组,则

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

可以通过点符号或括号符号访问对象属性(请参阅)

因此,这将输出您想要的:

console.log(Human[manAttributes[0]]);
您需要:

Human[manAttributes[0]]

[]
语法是通过(变量)名称而不是常量文字标记访问属性的方式。

您能发布代码吗?
function Human(age,name) {
  this.age = age;
  this.name = name;
}
var self = new Human(8,'Steve');

var humanProperties = Object.getOwnPropertyNames(self);

console.log(self[humanProperties[0]])
function Human(age,name) {
  this.age = age;
  this.name = name;
}
var self = new Human(8,'Steve');

var humanProperties = Object.getOwnPropertyNames(self);

console.log(self[humanProperties[0]])