我有一个名为 years
的 JavaScript 数组包含一些日期和一个文本项,如下所示:[ "2017", "2018", "2019", "historic" ]
我想对其进行排序,以便“历史”排在第一位,然后剩余的数字按数字排序。
除了 Firefox 之外,以下排序函数在我测试过的所有浏览器中都能完美运行,它会在数组末尾留下“历史”:
years.sort((a, b) => {
if (a === 'historic') {
return -1;
} else {
return a - b;
}
});
我尝试添加以下控制台日志:
let years = [ "2017", "2018", "2019", "historic" ];
years.sort((a, b) => {
console.log(a);
if (a === 'historic') {
return -1;
} else {
return a - b;
}
});
Firefox 输出以下内容:
2017 index.js:409
2018 index.js:409
2019
建议它永远不会处理“历史”数组元素。
最佳答案
您需要对两个元素进行对称检查,并检查值是否为'historic'
。然后返回支票的增量或值的增量。
var array = ["2017", "2018", "2019", "historic"];
array.sort((a, b) => (b === 'historic') - (a === 'historic') || a - b);
console.log(array);
关于javascript - 混合字母和数字内容的数组排序在 Firefox 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60430474/