javascript array.sort带有未定义的值 [英] javascript array.sort with undefined values
问题描述
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;
当调用 array.sort(function(l,r){.. 。});
值 undefined
从不传递为 l
或 r
。
我可以保证所有未定义的值会一直到所有浏览器的数组末尾?
以下循环处理数组中所有非 undefined
数据
array.sort();
for(var i = 0; array [i]!== undefined; i ++){
// handle array
}
您可以假设没有人声明未定义
为变量。
是的,你可以放心地假设 undefined
将被移动到数组的末尾。
从 MDC :
在JavaScript 1.2中,此方法不再将未定义的元素转换为null;而是将它们排序到数组的高端
从 spec,15.4.4.11
:
因为不存在的属性值总是比大于未定义的属性值,而
undefined总是比任何其他值大,未定义的属性值总是排序到结果的结尾,
后跟不存在的属性值
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.
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.
这篇关于javascript array.sort带有未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!