[英]Javascript - “concatenate” with a variable in a for loop
I am not really sure about the therm I use in my title, but here we go. 我不确定我在标题中使用的热敏电阻,但是现在就开始吧。
So I have something like that: 所以我有这样的事情:
for (var key in myObject) {
var GivenName = theObject.PS_1.GivenName;
var GivenName = theObject.PS_2.GivenName;
var GivenName = theObject.PS_3.GivenName;
var GivenName = theObject.PS_4.GivenName;
// and so on...
}
So obviously I don't wanna write everything like that, I need to use the var Key, but I didn't figure how the hell I am supposed to do that, I tried alof of thing, but I failed everytime, yes I'am bad and I should feel bad. 所以很明显我不想写那样的东西,我需要使用var Key,但是我没有弄清楚我该怎么做,我尝试了很多事情,但是每次都失败了,是的,不好,我应该感到难过。
I tried this: 我尝试了这个:
var GivenName = 'theObject.'+key+'.FirstName';
var GivenName = theObject.key.FirstName;
var GivenName = theObject.[key].FirstName;
var GivenName = theObject.['key'].FirstName;
var GivenName = theObject.[+key+].FirstName;
btw the Key var contain PS_1 then PS_2 then PS_3... btw Key var包含PS_1然后PS_2然后PS_3 ...
var GivenName = theObject[key].FirstName;
for (var key in myObject) {
var value = myObject[key];
}
If you haven't had a chance to read it yet the mozilla javascript documentation is absolutely awesome. 如果您没有机会阅读它,那么mozilla javascript文档绝对很棒。 https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
Even if you are familiar with most of it it will still provide excellent reference info. 即使您最熟悉它,它仍然会提供出色的参考信息。 From the docs:
从文档:
Object properties names can be valid JavaScript string, or anything that can be converted to string, including the empty string.
对象属性名称可以是有效的JavaScript字符串,也可以是任何可以转换为字符串的内容,包括空字符串。 However, any property name that is not a valid JavaScript identifier (for example, a property name that has space or dash, or starts with a number) can only be accessed using the square bracket notation.
但是,任何不是有效JavaScript标识符的属性名称(例如,具有空格或破折号或以数字开头的属性名称)都只能使用方括号符号来访问。 This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).
当要动态确定属性名称时(当直到运行时才确定属性名称时),该符号也非常有用。 Examples are as follows:
示例如下:
var myObj = new Object(),
str = "myString",
rand = Math.random(),
obj = new Object();
myObj.type = "Dot syntax";
myObj["date created"] = "String with space";
myObj[str] = "String value";
myObj[rand] = "Random Number";
myObj[obj] = "Object";
myObj[""] = "Even an empty string";
console.log(myObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.