简体   繁体   English

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

[英]Javascript, turn string into object attribute

I am wondering if it is possible to have an object with some attributes for example: 我想知道是否可能有一个带有某些属性的对象,例如:

object name: Human 对象名称:人

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

Then have an array of strings which contain each attribute to that object such as: 然后有一个字符串数组,其中包含该对象的每个属性,例如:

manAttributes = ["age","name"]

So therefore if i wrote 因此,如果我写

console.log(Human.manAttributes[0])

The console should log ' 8 ' But this doesn't work, I get unexpected string. 控制台应该记录“ 8 ”,但这不起作用,我得到了意外的字符串。

Thanks 谢谢

An object is a key:value pair. 对象是键:值对。 The key and value are separated by a : (colon). 键和值之间用:(冒号)分隔。 In your case, you have separated by = . 在您的情况下,您已用=分隔。 Change your code as below: 如下更改代码:

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

This solution considers manAttributes as a property of Human object. 此解决方案将manAttributes视为Human对象的属性。 If manAttributes is a separate array outside the Human object, then, 如果manAttributes是Human对象之外的单独数组,则,

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

if you are looking at iterating through the properties, i would suggest the following approach. 如果您正在遍历属性,我建议采用以下方法。

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]]);
  }  
} 

DEMO DEMO

Object properties can be accessed through either dot notation or bracket notation (see Mozilla's JavaScript reference ). 可以通过点表示法或括号表示法访问对象属性(请参见Mozilla的JavaScript参考 )。

So, this will output what you want: 因此,这将输出您想要的内容:

console.log(Human[manAttributes[0]]);

You'd be needing: 您需要:

Human[manAttributes[0]]

The [] syntax being the way of accessing a property by (variable) name rather than by constant literal token. []语法是通过(变量)名称而不是常量文字标记访问属性的方式。

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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM