Between them, the existing answers tell you everything, but none of them mention both of the problems in your code. Here's the full answer:
The sort isn't doing what you want because the default sort is lexical (i.e. the array elements are converted to strings and compared alphabetically). You can provide your own comparison function to sort()
:
x.sort(function(a, b) {
return a - b;
});
Secondly, for...in
is actually telling you nothing concrete about whether your array is sorted correctly, because the enumeration of for...in
is not defined (even though most but not all browsers do broadly what you'd expect). Use a for
loop instead (as indeed you generally should for arrays):
for (var i = 0, len = x.length; i < len; ++i) {
alert(x[i]);
}