javascript array.sort with undefined values

ぃ、小莉子 提交于 2020-01-09 07:52:07

问题


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) { ... }); The values undefined are never passed in as l or r.

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

Would the following loop handle all the non undefined data in an array

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

You may assume that no-one declared undefined as a variable.


回答1:


Yes, you can safely assume undefined will get 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 high end of the array

From the spec, 15.4.4.11 :

Because non-existent property values always compare greater than undefined property values, and undefined always compares greater than any other value, undefined property values always sort to the end of the result, followed by non-existent property values.




回答2:


It appears that the undefined values will fall to the bottom of the list. Here's some sample code to show you what happens:

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

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




回答3:


all undefined values will go to the end of the array regardless of their order in declaration. (at least this is how it works in chrome's js engine)




回答4:


Safari just deletes undefined property when calling sort(); method



来源:https://stackoverflow.com/questions/4783242/javascript-array-sort-with-undefined-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!