Recently encountered a problem:
Copy codeThe Code is as follows:
Var obj = {"name1": "Zhang San", "name2": "Li Si "};
Var key = "name1 ";
Var value = obj. key; // get "undefined"
Value = obj. name1; // you can obtain "Zhang San"
In fact, I want to dynamically assign values to the key and then obtain the value of the key pair. However, this method does not work. obj. key will find the value corresponding to the key "key" under obj. Of course the result cannot be found.
So I thought of how to traverse object attributes in js:
Copy codeThe Code is as follows:
Function printObject (obj ){
// Obj = {"cid": "C0", "ctext": "district/county "};
Var temp = "";
For (var I in obj) {// use javascript's for/in loop to traverse Object Attributes
Temp + = I + ":" + obj [I] + "\ n ";
}
Alert (temp); // result: cid: C0 \ n ctext: District/County
}
In this way, you can clearly know the key and value of an object in js.
Back to the question above, how can we dynamically assign values to the key and then get the corresponding value in the obj. key way?
In fact, the above printObject prompts that the obj [key] method can be used, and the key can be dynamic, which solves the problem I raised above.
Finally, there is another method, that is: eval ("obj." + key ).
Summary:
Js uses two methods to obtain the corresponding value of an object based on the dynamic key:
1. var key = "name1"; var value = obj [key];
Ii. var key = "name1"; var value = eval ("obj." + key );