for in语句与for in语句输入顺序问题
for in语句是一种精准的迭代语句,可以用来枚举对象的属性
1 var box={//这个对象有三个属性name、age、height 2 'name':'李某某', 3 'age':28, 4 'height':178 5 }; 6 7 for(var p in box){ 8 alert(p);//分别弹出name、age、height 9 }
for in 循环的输出顺序问题
1 var data = { 2 '4': 'first', 3 '3': 'second', 4 '2': 'third', 5 '1': 'fourth' 6 }; 7 8 for (var i in data) { 9 console.log(i + " " + data[i]) 10 }
IE11, chrome31, firefox23的打印如下:
1 1 fourth 2 2 third 3 3 second 4 4 first
1 var obj = { 2 "first":"first", 3 "zoo":"zoo", 4 "2":"2", 5 "34":"34", 6 "1":"1", 7 "second":"second" 8 }; 9 for (var i in obj) { console.log(i); };
IE11, chrome31, firefox23的打印如下:
1 1 2 2 3 34 4 first 5 zoo 6 second
事实上,它不一定根据定义时的顺数输出,所有浏览器的最新版本现在都按chrome执行,先把当中的非负整数键提出来,排序好输出,然后将剩下的定义时的顺序输出。由于这个奇葩的设定,只能强制用户不要以纯数字定义键名:
1 var obj = { 2 "first":"first", 3 "zoo":"zoo", 4 "2a":"2", 5 "34u":"34", 6 "1l":"1", 7 "second":"second" 8 }; 9 10 for (var i in obj) { console.log(i+" "+obj[i]); };
IE11, chrome31, firefox23的打印如下:
1 first first 2 zoo zoo 3 2a 2 4 34u 34 5 1l 1 6 second second