Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

sorting - 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) { ... }); 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...