javascript 带有未定义值的javascript array.sort

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4783242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:52:29  来源:igfitidea点击:

javascript array.sort with undefined values

javascriptsortingcross-browser

提问by Raynos

How does Array.prototype.sorthandle undefined values in an array?

如何Array.prototype.sort处理数组中的未定义值?

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 undefinedare never passed in as lor r.

调用时array.sort(function(l,r) { ... });undefined永远不会作为l或传入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 undefineddata in an array

以下循环会处理undefined数组中的所有非数据吗

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

You may assume that no-one declared undefinedas a variable.

您可以假设没有人声明undefined为变量。

采纳答案by Matt

Yes, you can safely assume undefinedwill get moved to the end of the array.

是的,您可以放心地假设undefined将移动到数组的末尾。

From MDC:

来自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

在 JavaScript 1.2 中,此方法不再将未定义的元素转换为 null;相反,它将它们排序到数组的高端

From the spec, 15.4.4.11 :

规范, 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.

因为不存在的属性值总是比未定义的属性值大,而未定义的值总是比任何其他值大,所以未定义的属性值总是排序到结果的末尾,然后是不存在的属性值。

回答by Sparafusile

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.

当然,这是 JavaScript 的默认行为。如果您覆盖默认行为,那么只有您自己知道。

回答by gaius_julius

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)

所有未定义的值都将到达数组的末尾,而不管它们在声明中的顺序如何。(至少这是它在 chrome 的 js 引擎中的工作方式)

回答by bldesign.ch

Safari just deletes undefinedproperty when calling sort();method

Safariundefined在调用sort();方法时只删除属性