简体   繁体   English

JS`array.sort`在IE6中失败,因为它的比较值不是数字。 怎么解决?

[英]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? 解决此问题的最佳方法是什么?

如果你想字符串之间的比较,并希望返回-101 ,使用localeCompare()

return a.name.localeCompare(b.name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Coffeescript array.sort(a,b)生成失败的JS - Coffeescript array.sort(a,b) generates failing JS JS Array.Sort IE 11与Chrome的区别 - Differences in JS Array.Sort IE 11 vs Chrome 带有多个值的JavaScript array.sort(字符串和数字) - JavaScript array.sort with multiple values (strings and numbers) IE Array.sort不使用比较功能进行排序 - IE Array.sort not sorting with compare function 如何将 JS Array.sort() 与具有不同属性的对象一起使用 - How to use JS Array.sort() with objects with different properties Return 1或-1如何在array.sort(a> b)(JS)中起作用/表示? 询问methos array.sort的过程 - How does Return 1 or -1 works/means in array.sort (a>b) (JS)? Asking about process of the methos array.sort JS中原生Array.sort()行为不一致 - Inconsistent native Array.sort() behavior in JS 带有未定义值的javascript array.sort - javascript array.sort with undefined values JS - 为什么 array.sort() 不会为对象和数字返回相同的结果? - JS - Why array.sort() doesn't return the same result for objects and numbers? 用点,字母,数字对对象数组进行排序。 我可以按数字排序,但是混合值很难。 不知道是否可能做对 - Sort array of objects with dots, letters, numbers. I was able to sort by numbers, but mixed values are difficult. Not sure if possible to do it right
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM