曾经听说,foreach的顺序是无法保证的,但同一对象在同一浏览器下遍历的顺序是固定的。
现在有需要通过foreach按一定顺序地遍历对象的成员(数据对象,key-value形式),所以做了一个小测试,测试各个浏览器顺序的差异。
结论:
IE6、IE7、IE8、Firefox、Safari是按照对象属性的初始化顺序来遍历的,与key的类型无关。
IE9、Chrome、Opera、360浏览器、遨游、搜狗浏览器、QQ浏览器,会对纯数字字符进行排序,输出顺序初步归纳如下:先纯数字字符,再其他;数字按照实际值由小到大输出;其他字符串按照初始化顺序输出。
由于我当时需要遍历的对象key是数字,这样在不同浏览器下面,数据出现的顺序会不一致。根据上面的测试结果,如果想统一他们的顺序,可以让纯数字字符变为混合字符,如在前面加下划线等等。
以下是测试代码:
<!DOCTYPE html> <html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> </head> <body> <script type="text/javascript"> var obj1 = {}; obj1["12"] = "先"; obj1["1"] = "后"; var tmp1 = "数字字符当key, 12:先,1:后 foreach结果:"; for (var name in obj1) { tmp1 += obj1[name]; } var obj2 = {}; obj2["1"] = "先"; obj2["12"] = "后"; var tmp2 = "数字字符当key,将key-value交叉对调, 1:先,12:后 foreach结果:"; for (var name in obj2) { tmp2 += obj2[name]; } var obj3 = {}; obj3["cd"] = "先"; obj3["a"] = "后"; var tmp3 = "英文字符当key, cd:先,a:后 foreach结果:" for (var name in obj3) { tmp3 += obj3[name]; } var obj4 = {}; obj4["cd"] = "先"; obj4["a"] = "后"; var tmp4 = "英文字符当key,将key-value交叉对调 a:先,cd:后 foreach结果:" for (var name in obj4) { tmp4 += obj4[name]; } var obj5 = {}; obj5["_2"] = "先"; obj5["_1"] = "后"; var tmp5 = "符号+数字当key, _2:先,_1:后 foreach结果:" for (var name in obj5) { tmp5 += obj5[name]; } var obj6 = {}; obj6["_2"] = "先"; obj6["_1"] = "后"; var tmp6 = "符号+数字当key,将key-value交叉对调 _1:先,_2:后 foreach结果:" for (var name in obj6) { tmp6 += obj6[name]; } var obj7 = {}; obj7["1"] = "先"; obj7["a"] = "后"; var tmp7 = "纯数字字符、纯英文字符当key, 1:先,a:后 foreach结果:" for (var name in obj7) { tmp7 += obj7[name]; } var obj8 = {}; obj8["1"] = "第一"; obj8["12"] = "第二"; obj8["3"] = "第三"; obj8["a1"] = "第四"; obj8["1a"] = "第五"; obj8["a"] = "第六"; obj8["zzz"] = "第七"; var tmp8 = "纯数字字符、混合字符、纯英文字符 1:第一,12:第二,3:第三,a1:第四,1a:第五,a:第六,zzz:第七 foreach结果:" for (var name in obj8) { tmp8 += obj8[name]; } var obj9 = {}; obj9["zzz"] = "第一"; obj9["1"] = "第二"; obj9["12"] = "第三"; obj9["a"] = "第四"; obj9["3"] = "第五"; obj9["a1"] = "第六"; obj9["1a"] = "第七"; var tmp9 = "纯数字字符、混合字符、纯英文字符 zzz:第一,1:第二,12:第三,a:第四,3:第五,a1:第六,1a:第七 foreach结果:" for (var name in obj9) { tmp9 += obj9[name]; } document.write(tmp1 + "<br/>" + tmp2 + "<br/>" + tmp3 + "<br/>" + tmp4 + "<br/>" + tmp5 + "<br/>" + tmp6 + "<br/>" + tmp7 + "<br/>" + tmp8 + "<br/>" + tmp9 + "<br/>"); </script> </body> </html>
以下是测试结果截图: