[英]JS `array.sort` failing in IE6 because its compared values are not numbers. How to resolve?
I have the following sort function which attempts to sort the items based on whether they start with a value entered into a text box. 我具有以下排序功能,该功能试图根据项目是否以在文本框中输入的值开头来对项目进行排序。
items.sort(function(a, b) {
var aStart = a.name.match(new RegExp('^' + textEntered, 'i')) || [];
var bStart = b.name.match(new RegExp('^' + textEntered, 'i')) || [];
if (aStart.length != bStart.length) {
return bStart.length - aStart.length;
}
else {
return b.name - a.name; // error because these aren't numbers
}
return 0;
});
This works in every browser I've tried it in, except for IE6, which returns an error stating that it expected a number. 这适用于我尝试过的所有浏览器,但IE6除外,IE6返回一个错误,指出它需要一个数字。
I tried to implement the suggested fix from this article, which suggests "Don't reuse the argument variables inside of an Array sort function.": http://www.zachleat.com/web/array-sort with the following: 我试图实现本文建议的修复,该修复建议“不要在Array排序函数内部重用参数变量。”: http : //www.zachleat.com/web/array-sort包含以下内容:
items.sort(function(a1, b1) {
var a, b;
a = a1;
b = b1;
var aStart = a.name.match(new RegExp('^' + textEntered, 'i')) || [];
var bStart = b.name.match(new RegExp('^' + textEntered, 'i')) || [];
if (aStart.length != bStart.length) {
return bStart.length - aStart.length;
}
else {
return b.name - a.name;
}
return 0;
});
but it doesn't have any effect. 但这没有任何作用。 Has anyone had to deal with this before?
以前有人要处理吗? What's the best fix for this issue?
解决此问题的最佳方法是什么?
如果你想字符串之间的比较,并希望返回-1
, 0
或1
,使用localeCompare()
return a.name.localeCompare(b.name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.