Alex Rivera | Logout

Why doesn't the sort function of javascript work well?

Asked 2011-05-23T06:59:33.080
21

This simple javascript

var x = new Array();
x[0] = 2.73;
x[1] = 11.17;
x[2] = 3.12
x.sort();

for(var i in x)
    alert(x[i]);

produces the results: 11.17, 2.73, 3.12 instead of 2.73, 3.12, 11.17.

Why is that and how can I fix it?

Thanks in advance!

Edit
Report

1 Answer

2

You are not iterating properly. It should be:

for (var i = 0; i < x.length; i++) {
    alert(x[i]);
}

When you use for..in in javascript this will loop through the properties of the object and the order of iteration is undefined. You should be seeing some strange output as well such as all the functions defined in the Array class.

answered 2011-05-23T07:01:56.927

Your Answer