From the object format, we can see that if the string format is defined as json, it can be directly converted to obj. If you are interested, refer
JavaScript Object definition method
1. var obj = new Object ()
The Code is as follows:
New Document
Script
Var obj = new Object ();
Obj. key = "11 ";
Alert (obj. key );
Script
2. var obj = {};
The Code is as follows:
New Document
Script
Var obj = {};
Obj. key = "11 ";
Alert (obj. key );
Script
You can also initialize the value at definition:
Var obj = {key: '11 '};
How to convert an object to a string
If you directly use:
The Code is as follows:
Obj. toString ()
The result 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.
The Code is as follows:
New Document
Script
Var obj = {attr1: 'value1', attr2: 'value2 '};
For (attr in obj)
{
Alert (attr );
Alert (eval ("obj." + attr ));
}
Script
It focuses on why the value is used:
The Code is as follows:
Eval ("obj." + attr );
Instead of directly using
The Code is as follows:
Obj. attr
Because the key value in obj. 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 String to object
From the object format, we can see that if the string format is defined as json, it can be directly converted to obj.
Compare the following two methods:
The Code is as follows:
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.