Google Custom Search

2013/06/10

Chrome會對key為數字的陣列自動排序


根據:
http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
提到:
Numerically named properties in Chrome
Chrome browsers process numerically named keys first and in numeric sequence not insertion sequence.
1
2
3
4
5
6
7
8
9
var obj = {3:'a', 2:'b', 'foo':'c', 1:'d'}, result = [];
for (var prop in obj) {
    result.push(prop);
}
result.toString();
//Chrome -> "1,2,3,foo"
//Other browsers -> "3,2,foo,1"
自作聰明,陣列排序自有其意義,有需要自然會sort,害人多花時間除錯。

必須先用文字取代key,進入回圈後再還原成數值。