Conversion between JavaScript objects and strings

Source: Internet
Author: User
JavaScript Object definition method 1. varobjnewObject () [html] & lt ;! -- Addbyoscar999 -- & gt; & lt ;! DOCTYPEHTMLPUBLIC & quot;-// W3C // DTDHTML4.0Transitional // EN & quot; & gt; & lt; HTML & gt; & lt; HEAD & JavaScript Object definition method 1. var obj = new Object () [html] New Document Script var obj = new Object (); obj. key = "11"; alert (obj. key); script2. var obj = {}; [html] New Document Script var obj ={}; obj. key = "11"; alert (obj. key); scriptYou can also initialize the value: var obj = {key: '11'} at the time of definition. How to convert an object to a string? If you directly use: [javascript] obj. toString () is a string like [object, object. As shown in the second definition (var obj = {key: '11, the string class corresponding to the js object is a pair of key-value pairs enclosed in braces. It is actually the JSON data format. If you are not familiar with it, you can learn the json format. You can use the following method to retrieve the key and value of obj. [Html] New Document Script var obj = {attr1: 'value1', attr2: 'value2'}; for (attr in obj) {alert (attr); alert (eval ("obj. "+ attr);} scriptIt focuses on why the value is used: [javascript] eval ("obj. "+ attr), instead of directly using [javascript] obj. attr because obj. the key value of obj found by attr is the value of attr, but obj does not have the key value of attr. The attr here is a variable. Therefore, it is necessary to use the eval method. How to convert a String to an object can be seen from the object format. If the String format is defined as json, it can be directly converted to obj. Compare the following two methods: [javascript] var obj1 = {attr1: 'value1', attr2: 'value2'}; var obj2 = "{attr1: 'value1 ', attr2: 'value2'} "; obj1 is an object directly, and obj2 is just a string. You can use eval (obj2) to convert it to an object. Why does this happen: in many cases, we will return this string from the server for front-end processing.

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.