Home >Web Front-end >JS Tutorial >JavaScript for-in traverses json data in order and explores differences between browsers_javascript skills
Object itself is a collection without objects, so when using the for-in statement to traverse the properties of the object, the order of the properties traversed is different from that when the object is defined.
Learn about W3C standards:
According to the third edition of ECMA-262 (ECMAScript), the order of attribute traversal in the for-in statement is determined by the writing order of the attributes when the object is defined.
For more information about the for-in statement in ECMA-262 (ECMAScript) 3rd Edition, please refer to 12.6.4 The for-in Statement in ECMA-262 3rd Edition.
In the latest ECMA-262 (ECMAScript) fifth edition specification, the traversal mechanism of the for-in statement has been adjusted, and the order of attribute traversal is not specified.
For more information about the for-in statement in ECMA-262 (ECMAScript) 5th Edition, please refer to 12.6.4 The for-in Statement in ECMA-262 5th Edition.
The attribute traversal order description in the new version is different from that of the earlier version, which will cause the JavaScript parsing engine implemented following the ECMA-262 third edition specification to process for-in statements differently from the parsing implemented following the fifth edition specification. Engine, there is an inconsistency issue with the traversal order of properties.
Therefore, during development, you should try to avoid writing code that relies on the order of object properties. As follows:
<script> var json1 = { "2":{"name":"第1条"}, "1":{"name":"第2条"}, "3":{"name":"第3条"} } var json2 = [ {"name":"第1条"}, {"name":"第2条"}, {"name":"第3条"} ] for(var i in json1){ alert(json1[i].name); } //正确 for(var i in json2){ alert(json2[i].name); } </script>
Look at the differences in the for-in code in each browser:
The following is a separate code introduction to JS looping through JSON data
JSON data such as:
{"options":"[{/"text/":/"王家湾/",/"value/":/"9/"},{/"text/":/"李家湾/",/"valu e/":/"10/"},{/"text/":/"邵家湾/",/"value/":/"13/"}]"}
can be written in js as:
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
<script type="text/javascript"> function text(){ var json = {"options":"[{/"text/":/"王家湾/",/"value/":/"9/"},{/"text/":/"李家湾/",/"value/":/"10/"},{/"text/":/"邵家湾/",/"value/":/"13/"}]"} json = eval(json.options) for(var i=0; i<json.length; i++) { alert(json[i].text+" " + json[i].value) } } </script>