How does js obtain the key values of the object type?

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.