May 08, 2021 JSON
Object itself is a collection of objectless objects, so when you traverse an object's properties with a for-in statement, the order of properties that are traversed is different from when the object is defined.
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);
}
Look at the for-in code differences in a browser:
Here's a separate introduction to the JS loop traversing the JSON data through a piece of code
JSON data such as:
"Options": "text/":/"Wangjiawan/""value/"
e/:/"10/",""text":/"Yujiawan/", /"value/":/"13"
With js you can write:
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>
There are two ways to traverse an array in js
var array = ['a']
//标准的for循环
for (var i = 1; i < array.length; i++) {
alert(array[i])
}
//foreach循环
for (var i in array) {
alert(array[i])
}
Normally the above two traverses the array in the same way. Let's start with the first difference between the two
The standard for loop i is the number type, which represents the subsume of the array, but the i in the foreach loop represents that the key of the array is the string type because everything in js is an object. T ry alert yourself (typeof i); T his difference is a minor problem. Now I add the following code, the above execution results are not the same.
//扩展了js原生的Array
Array.prototype.test=function(){
}
Two more suggestions
1. Don't traverse arrays with for in, all unified with standard for-loop variable arrays (we can't guarantee whether the js we introduced will use prototype extension native Arry)
2. If you want to extend the native class of js, don't use prototype