JS排序适用于Firefox但不适用于IE - 无法解决原因

时间:2010-06-02 09:35:29

标签: javascript jquery

我在javascript函数中有一行,它根据另一个字符串数组的顺序对一个对象数组进行排序。这是在Firefox中工作但不在IE中,我不知道为什么。这是我的数据在IE7中进入排序调用的样子。 (我正在使用三个项目的数组来说明这一点。)

//cherry first then the rest in alphabetical order
originalData = ['cherry','apple','banana','clementine','nectarine','plum']

//data before sorting - note how clementine is second item - we wan to to to be after apple and banana
csub = [
  {"value":"cherry","data":["cherry"],"result":"cherry"},
  {"value":"clementine","data":["clementine"],"result":"clementine"},
  {"value":"apple","data":["apple"],"result":"apple"},
  {"value":"banana","data":["banana"],"result":"banana"},
  {"value":"nectarine","data":["nectarine"],"result":"nectarine"},
  {"value":"plum","data":["plum"],"result":"plum"}
]

//after sorting, csub has been rearranged but still isn't right: clementine is before banana. in FF it's in the right place.
csubSorted = [
  {"value":"cherry","data":["cherry"],"result":"cherry"},
  {"value":"apple","data":["apple"],"result":"apple"},
  {"value":"clementine","data":["clementine"],"result":"clementine"},
  {"value":"banana","data":["banana"],"result":"banana"},
  {"value":"nectarine","data":["nectarine"],"result":"nectarine"},
  {"value":"plum","data":["plum"],"result":"plum"}
]

这是实际的排序代码:

 csubSorted = csub.sort(function(a,b){ return (originalData.indexOf(a.value) > originalData.indexOf(b.value)); });

谁能明白为什么这不起作用?基本的javascript排序功能是不是跨浏览器兼容的?我可以用不同的方式(例如使用jquery)进行跨浏览吗?

感谢任何建议 - 最多

编辑 - 这也无法在safari和chrome中运行 - 换句话说,它似乎只能在firefox中运行。

已解决 - 感谢Tim Down。 我实际上使我的代码更简单,因为我意识到我需要的顺序始终是“返回数组中的第一项,后面是使用.value排序的其余数组”。所以,我改变了我的代码:

  first = csub.shift();
  csubSorted = csub.sort(function(a,b){ 
    return (a.value > b.value); 
  });
  csubSorted.unshift(first);

但是,它仍然无效。然后Tim(下面)指出sort希望从函数返回-1,0或1,not true或false,这是我的代码返回的。显然,firefox可以让你逃避这一点,但其他浏览器却没有。所需要的只是将'或'转换为真或假为1和-1(我不担心两个字符串都是samae的情况,实际上会返回为-1,这对于无论如何排序顺序):

  first = csub.shift();
  csubSorted = csub.sort(function(a,b){ 
    return (a.value > b.value ? 1 : -1); 
  });
  csubSorted.unshift(first);
Tim还告诉我,IE中不支持array.indexOf()这很烦人,即使我不在这里使用它,我在其他位代码中使用它。 Goddamit。是否有某个API页面最终只列出了跨浏览器兼容的javscript API?

1 个答案:

答案 0 :(得分:9)

首先,在IE< = 8中没有数组的indexOf方法。你需要自己编写。其次,传递给Array的sort()方法的比较函数应该返回一个数而不是一个布尔值。

var indexOf = (typeof Array.prototype.indexOf == "function") ?
    function(arr, val) {
        return arr.indexOf(val);
    } :

    function(arr, val) {
        for (var i = 0, len = arr.length; i < len; ++i) {
            if (typeof arr[i] != "undefined" && arr[i] === val) {
                return i;
            }
        }
        return -1;
    };

csubSorted = csub.sort(function(a,b){
    return indexOf(originalData, a.value) - indexOf(originalData, b.value);
});