Javascript array.sort with undefined values

How does Array.prototype.sort handle undefined values ​​in an array?

 var array = [1,undefined,2,undefined,3,undefined,4]; var array2 = []; array2[0] = 1;array2[2] = 2;array2[4] = 3;array2[6] = 4; 

When calling array.sort(function(l,r) { ... }); Undefined values ​​are never passed as l or r .

Can I guarantee that all undefined values ​​will always go to the end of the array for all browsers?

Will the next loop process all data not undefined in the array

 array.sort(); for (var i = 0; array[i] !== undefined; i++) { // handle array } 

You can assume that no one declared undefined as a variable.

+12
source share
4 answers

Yes, you can safely assume that undefined will be moved to the end of the array.

From MDC :

In JavaScript 1.2, this method no longer converts undefined elements to null; instead, it sorts them to the upper end of the array

From spec, 15.4.4.11 :

Because the values ​​of non-existent properties are always compared with the values ​​of undefined properties and undefined is always compared more than any other value, the values ​​of undefined properties are always sorted to the end of the result, followed by non-existent property values.

+11
source

It looks like undefined values ​​will fall at the bottom of the list. Here are some sample code to show you what is happening:

 var a = [1,undefined,2,undefined,3,undefined,4]; a = a.sort(); for( i = 0 ; i < a.length ; i++ ) { alert( a[i] ); } 

This, of course, is the default JavaScript behavior. If you overwrite the default behavior, then you will only find out.

0
source

all undefined values ​​will go to the end of the array, regardless of their order in the declaration. (at least that's how it works in the chrome js processor)

-one
source

Safari simply removes the undefined property when calling the sort(); method sort();

-4
source

All Articles