This article mainly introduced JS to get the object type in the key value of the method, the need for friends can refer to the
Recently encountered a problem:
The code is as follows:
var obj = {"name1": "John", "name2": "Dick"};
var key = "Name1";
var value = obj.key;//got "undefined"
Value = obj.name1;//got "John"
In fact, I want to dynamically assign value to the key, and then get the value of how much key is right. But this approach does not work, Obj.key will find obj under key for "key" corresponding to the value, the result of course is not found it.
So, I think of JS in the Traversal object properties method:
The code is as follows:
function PrintObject (obj) {
obj = {"cid": "C0", "Ctext": "Counties"};
var temp = "";
for (var i in obj) {//For/in looping through the properties of the object with JavaScript
Temp + + i+ ":" +obj[i]+ "n";
}
Alert (temp);//Result: cid:c0 N ctext: Counties
}
In this way, you can clearly know what is the key and value of JS one object is what.
Back to the problem, how to dynamically assign a value, and then obj.key to get the corresponding value?
In fact, the above PrintObject has a hint, that is, using the Obj[key] method, key can be dynamic, so that solves the problem I raised above.
Finally, there is another way to do this: eval ("obj.") +key).
Summarize:
JS in the dynamic key to obtain the corresponding value of the object is two methods:
First, var key = "Name1"; var value = Obj[key];
Second, var key = "Name1"; var value = eval ("obj.") +key);