This article mainly introduces javascriptfor-in to traverse json data in an orderly manner and explore the information about the differences between browsers. For more information, see object itself as a collection of objects, therefore, when we use the for-in statement to traverse the attributes of an object, the order of the retrieved attributes is different from that of the object definition.
Understand W3C standards:
As described in the third edition of ECMA-262 (ECMAScript), the order in which for-in statements traverse properties is determined by the order in which attributes are written when the object is defined.
For more information about The for-in Statement in The third Edition of ECMA-262, see 12.6.4 The for-in Statement in ECMA-262 3rd Edition.
In the latest ECMA-262 (ECMAScript) Fifth Edition specification, the for-in statement traversal mechanism has been adjusted, the order of attribute traversal is not specified.
For more information about The for-in Statement in ECMA-262 (ECMAScript) Fifth Edition, see 12.6.4 The for-in Statement in ECMA-262 5rd Edition.
The attribute traversal order in the new version is different from that in earlier versions, which will lead to JavaScript parsing engines implemented following the ECMA-262 third-edition specification when processing for-in statements, the traversal sequence of attributes is inconsistent with the parsing engine implemented in compliance with the fifth edition specification.
Therefore, we should try to avoid writing code that depends on the object attribute sequence during development. As follows:
Script var json1 = {"2": {"name": "1st"}, "1": {"name": "2nd "}, "3": {"name": "3rd"} var json2 = [{"name": "1st" },{ "name ": "2nd" },{ "name": "3rd"}] for (var I in json1) {alert (json1 [I]. name);} // correct for (var I in json2) {alert (json2 [I]. name);} script
Let's take a look at the differences between the for-in code in different browsers:
The following code is used to introduce the JS loop traversal of JSON data.
JSON data such:
{"Options": "[{/" text/":/" wangjiawan/",/" value/":/" 9/"},{/" text /": /"Li jiawan/",/"value/":/"10/"}, {/"text/":/"Shao jiawan/",/"value /": /"13/"}] "}
Javascript can be written as follows:
var data=[{name:"a",age:12},{name:"b",age:11},{name:"c",age:13},{name:"d",age:14}]; for(var o in data){ alert(o); alert(data[o]); alert("text:"+data[o].name+" value:"+data[o].age ); }
Or