2016-09-07 149 views
0

我有一个非常简单的排序功能,通过index排序对象:排序功能在IE浏览器不工作11

panoramas.sort((a, b) => { 
    if (a.index > b.index) return 1 
}) 

输入:

[ 
    { index: 0 }, 
    { index: 2 }, 
    { index: 1 } 
] 

输出:

[ 
    { index: 1 }, 
    { index: 2 }, 
    { index: 3 } 
] 

功能适用于Chrome和Firefox,但不适用于IE(阵列根本没有分类)

我的功能有问题吗?

+0

我想* *它不排序,因为你的函数的情况下'没有明确的返回值a.index <= b.index'。 –

+0

@MartinNyolt我应该如何更改代码以反映这一点? – alex

+0

请参阅[此答案](http://stackoverflow.com/a/24080786/1314743)。 –

回答

2

对于排序,排序函数应该返回-1,0或1。

// Your function tests for 'a.index > b.index' 
// but it's missing the other cases, returning false (or 0) 

panoramas.sort((a, b) => { 
    if (a.index > b.index) return 1; 
    if (a.index < b.index) return -1; 
    return 0; 
}) 

Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?

  • > 0a被认为大于b和后应进行排序它
  • == 0a被认为等于b并不要紧先来吧
  • < 0a被认为是小于b,应进行排序之前

对数字,你可以用一个更简洁的方法:

panoramas.sort((a, b) => { 
    return a.index - b.index; 
    // but make sure only numbers are passed (to avoid NaN) 
}) 

IE11,正如@teemu 所述,不支持箭头功能,你必须使用函数表达式:


panoramas.sort(function(a, b) { 
    return a.index - b.index; 
}); 
+0

'return a.index - b.index'更加简洁。 –

+0

thnx @MartinNyolt。有详细的解决方案,因为我认为它会更容易理解 – bfmags

相关问题