【问题标题】:Array remains unchanged when using sort on it对数组使用排序时数组保持不变
【发布时间】:2023-01-04 16:01:58
【问题描述】:

我想对天数数组进行排序,我发现使用预定义的数组引用比 JS Date 类方法更好。

调用排序的我的数组没有排序,即使我在回调中总是return 1,数组也永远不会改变。

const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];

toSort.sort((a, b) => {
  a = days.indexOf(a);
  b = days.indexOf(b);

  return a < b ? 0 : 1;

  // No matter what I return, the source array remains unchanged
  return a < b ? 1 : 0;
  return 1;
});

console.log(toSort);

使用基本的 JS 函数出现如此混乱的情况(哈哈明白了)一定意味着答案非常明显,但我无法弄清楚。

【问题讨论】:

    标签: javascript sorting


    【解决方案1】:

    const days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
    
    const toSort = ["monday", "tuesday", "thursday", "friday", "wednesday"];
    
    toSort.sort((a, b) => {
      a = days.indexOf(a);
      b = days.indexOf(b);
    
      return a < b ? -1 : 1;
    
      return a < b ? 1 : 1;
      return 0;
    });
    
    console.log(toSort);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2022-01-10
      • 2010-10-04
      • 1970-01-01
      • 2020-12-13
      相关资源
      最近更新 更多