IE在比较字符串时的预期错误数

Number expected error in IE on comparing strings

本文关键字:错误 比较 字符串 IE      更新时间:2023-09-26

我在一个javascript插件中有一个排序函数,代码看起来像这样:

groups = groups.sort(function (a, b) {
    a = a.content.toString().toLowerCase().replace(/'s+/g, '');
    b = b.content.toString().toLowerCase().replace(/'s+/g, '');
if(a > b){ //stops and gives error here
return 1;
}
if(a < b){
return -1;
}
return 0;
});

a.content实际上是一个字符串本身(但只是为了IE的缘故,我在代码中添加了.toString()
在所有其他浏览器上,上面的代码在所有浏览器上运行良好,但在IE 8上,上面的代码显示了一个JavaScript错误,并停在上面代码中所示的行。控制台在这一行显示一条消息"Number expected"。

(有时a.content也可能在这个表单中有一些html ->
"<span>Sample String</span>"
不确定这是否会导致IE8的错误,但这个问题只发生在这个浏览器中)
如何消除这个错误?

a = a.content.toString().toLowerCase()

用这个代替

var a1 =    a = a.content.toString().toLowerCase()

因为ie <9与toLowerCase返回未知数据类型随机…如果你不在sort中重新赋值变量,它就会正常工作。

我记得在IE中添加一些空白时出现了一些问题…试着修剪。

还是……你是否尝试使用。localecompare比较字符串?

alert('a'.localeCompare('b'));
alert('a'.localeCompare('a'));
alert('b'.localeCompare('a'));