how JavaScript objects are defined
1. var obj = new Object ()
Copy Code code as follows:
<!--ADD by oscar999-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "Author" content= "oscar999" >
<script>
var obj = new Object ();
Obj.key = "11";
alert (Obj.key);
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
2. var obj = {};
Copy Code code as follows:
<!--ADD by oscar999-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "Author" content= "oscar999" >
<script>
var obj = {};
Obj.key = "11";
alert (Obj.key);
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
You can also initialize values at the time of definition:
var obj = {key: ' 11 '};
How objects are converted into strings
If used directly:
Copy Code code as follows:
Get a string of [Object,object].
From the second defined method above (var obj = {key: ' one '};) It can be seen that the JS object corresponding to the string class is a pair of curly braces wrapped in a number of key values in the way.
In fact, JSON is the data format, do not understand the JSON format can be learned.
You can remove the key and value of obj using the following methods.
Copy Code code as follows:
<!--ADD by oscar999-->
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<meta name= "Author" content= "oscar999" >
<script>
var obj = {attr1: ' value1 ', attr2: ' value2 '};
for (attr in obj)
{
alert (attr);
Alert (eval ("obj.") +ATTR));
}
</script>
</HEAD>
<BODY>
</BODY>
</HTML>
Focus on why the value is used:
Copy Code code as follows:
Rather than directly using
Copy Code code as follows:
Because the value of the key in obj found by obj.attr is attr, there is no attr key value in obj.
The attr here is a variable. So we have to use the eval way.
how String is converted to an object
As you can see from the format of the object, if the format of the string is defined in JSON format, you can convert it directly to obj.
Compare the following two ways:
Copy Code code as follows:
var obj1 = {attr1: ' value1 ', attr2: ' value2 '};
var obj2 = "{attr1: ' value1 ', attr2: ' value2 '}";
Obj1 is directly an object, Obj2 is just a string.
You can convert to an object by using eval (OBJ2).
Why is this usage: because very often, we return this word falsify front-end processing from the service side.