Why does sorting a JS array of numbers with < work?

前端 未结 5 1743
一生所求
一生所求 2020-12-06 10:58

When sorting an array of numbers in JavaScript, I accidentally used < instead of the usual - -- but it still works. I wonder why?

Ex

5条回答
  •  难免孤独
    2020-12-06 11:51

    If we analyze what's being done, it seems that this is mostly luck as in this case, 3 and 2 are considered to be "the same" and should be interchangeable. I suppose in such cases, the JS engines keep the original order for any values that have been deemed equal:

    let a = [1, 3, 2, 4];
    a.sort((n1, n2) => {
      const result = n1 < n2;
      if (result < 0) {
        console.log(`${n1} comes before ${n2}`);
      } else if (result > 0) {
        console.log(`${n2} comes before ${n1}`);
      } else {
        console.log(`${n1} comes same position as ${n2}`);
      }
      return result;
    })
    
    console.log(a);

    As pointed out in the comments, this isn't guaranteed to work ([1,2,1,2,1,2,1,2,1,2,1,2] being a counter-example).

提交回复
热议问题