Javascript - Opera 11.60 和 IE 8 上的排序功能问题
我正在尝试按属性对对象进行排序。我的功能在 Opera 和 IE 上遇到问题。到目前为止,我已经在 Opera 上调试了这个阶段的问题:
- 打开“Opera 浏览器”并按 cntr+shift+i。选择控制台。
-
在控制台中传递此代码并按 Shift+Enter。
var DataArray=["其他","态度","态度","交货/时间","一般表现","个人规划","其他"] DataArray=DataArray.sort(函数(a,b) { 返回 a
你应该得到这样的正确结果:
<块引用>["个人规划","其他","其他","一般表现","交付/时间","态度","态度"]
-
现在以这种方式更改排序功能 a>b 像这样按 Enter+Shift 执行它。
var DataArray=["其他","态度","态度","交货/时间","一般表现","个人规划","其他"] DataArray=DataArray.sort(函数(a,b) { 返回a>b; }); JSON.stringify(DataArray);
我的结果是:
<块引用>[“态度”、“交付/时间”、“态度”、“总体表现”、“其他”、“其他”、“个人规划”]
请注意第一个、第二个和第三个值?这是怎么回事?
如果您在控制台“Attitude”=“Attitude”中执行此操作,它将返回 true...
有什么想法吗?
提前致谢。
编辑: 带有 IE 的部分:
代码:
var DataArray=['Other','Attitude','Attitude','Delivery/timings','General Performance','Personal Planning','Other'];
DataArray=DataArray.sort(function(a,b)
{
return a<b;
});
prompt('',DataArray);
结果(正确):个人计划、其他、其他、一般表现、态度、态度、交货/时间
代码:
var DataArray=['其他'、'态度'、'态度'、'交付/时间”、“总体表现”、“个人规划”、“其他”];
DataArray=DataArray.sort(function(a,b)
{
return a>b;
});
prompt('',DataArray);
结果(不正确):态度、态度、其他、交货/时间、一般表现、其他、个人计划
解决方案:
sortableArray=sortableArray.sort(function(a,b)
{
if(a.Category>b.Category)
{
return 1;
}
if(a.Category<b.Category)
{
return -1;
}
return 0;
});
要按降序方式对数据进行排序,请使用reverse()函数。
谢谢你的帮助。特别是@nnnnnn
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是任何特定浏览器的问题,而是没有阅读
.sort()
函数文档。您传递给.sort()
的回调不应该返回布尔值,它应该返回一个数字:This isn't a problem with any particular browser, it is a problem with not having read the
.sort()
function documentation. The callback you pass to.sort()
is not supposed to return a boolean, it is supposed to return a number that is:您的排序函数返回一个布尔值,而它应该返回一个整数。虽然
1
可能会被混淆为true
,而0
会被混淆为false
,但这不应该是您依赖的东西代码逻辑开启。该函数应该有 3 个返回情况:< 0
如果a > b
> 0 如果
a
b
== 0
ifa == b
所以你应该像这样对数组进行排序:
这是一个 工作演示。
Your sorting function returns a boolean value, while it should return an integer. While
1
can be confused astrue
and0
asfalse
, this shouldn't be something that you rely your code logic on. The function should have 3 return cases :< 0
ifa > b
> 0
ifa < b
== 0
ifa == b
So you should use sort your array like this :
Here's a working demo.