Javascript – Array.sort() doesn’t sort numbers correctly

javascript

In Chrome 14, and Firefox 5 (haven't tested other browsers), the following code doesn't sort the numbers correctly:

<script>
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);


document.write(a.sort())
</script>

It returns 10,100,20,30,60

I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?

Best Answer

a.sort(function(a,b){return a - b})

These can be confusing.... check this link out.