排序功能在IE 11中不起作用

Sorting function not working in IE 11

本文关键字:不起作用 IE 功能 排序      更新时间:2023-09-26

>我有一个非常简单的排序函数,可以按index对对象进行排序:

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(数组根本没有排序(。

我的功能有问题吗?

排序

函数应返回 -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;
})

来自 JavaScript 中的排序:返回布尔值对于比较函数来说不应该足够吗?

  • > 0 a何时被认为大于b,并应在它之后排序
  • == 0a被认为等于b并且哪个先到并不重要
  • < 0 a何时被视为小于 b 并应在它之前排序

对于数字,您可以使用更简洁的方法:

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

对于 IE11,如 @teemu 所述,不支持箭头函数,您必须使用函数表达式:

  • http://caniuse.com/#feat=arrow-functions

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