开发者

Simple sorting function fails in IE7

I have been staring myself blind at this piece of javascript code, I need some help.

It is a case insensitive sort function that will properly handle special (danish) characters, however it refuses to work in IE7 and I cannot see any reason why it should not work. It is not that fancy...

function _compare(a, b) {
    var sortorder = " 0123456789.abcdefghijklmnopqrstuvwxyzæøå",
        min = 0,
        idx = 0,
        c = 0;
    a = ' ' + a;
    b = ' ' + b;
    a = a.substring(1).toLowerCase();
    b = b.substring(1).toLowerCase();

    min = Math.min(a.length, b.length);

    while (idx < min &开发者_Python百科;& a[idx] == b[idx]) {
        idx++;
    }

    if (idx == min) {
        if (a.length > b.length) {
            c = 1;
        }
        else if (a.length < b.length) {
            c = -1;
        }
    }
    else {
        c = (sortorder.indexOf(a[idx]) > sortorder.indexOf(b[idx])) ? 1 : -1;
    }

    return c;
}

var key, ar = [];

ar.push("TEST");
ar.push("abcd");
ar.push("test");
ar.push("øæå!");
ar.push("oåø!");
ar.push("åæø!");
ar.push("aaø!");

ar.sort(_compare);

for (key in ar) {
    $("pre").append(ar[key] + "<br />");
}

http://jsfiddle.net/hpvek/ - it works as excepted in FF, Chrome, IE8-9 and Safari. IE7 (possible IE6, which I do not have in my testing arsenal) seems the odd man out.

thanks for any help.


for (key in ar) {
    $("pre").append(ar[key] + "<br />");
}

This is the wrong way to iterate over an array if you want to preserve the order.

Though, it's not the problem here it seems.

Gosh, it was simple. IE doesn't support treating strings like arrays. You have to convert them into arrays to lookup the idx index or use charAt.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜