我正在尝试对包含空字符串、数字、“infinity”、“-infinity”和“NaN”的数组进行排序。我收到了所有字符串形式的值,因此当涉及到空字符串、inf 和 nan 时,sort 无法按预期工作。有没有一种方法可以按升序和降序自定义我的排序功能?
最佳答案
您可以使用一个对象来排序并将给定的项目移动到想要的位置。
var array = ["", 2, 3, 0, "inf", "-inf", "Nan", -1, -100000];
array.sort(function (a, b) {
var order = { "": -4, "-inf": -3, "Nan": -2, "inf": -1 };
return (order[a] || 0) - (order[b] || 0) || a - b;
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何对包含空字符串、NaN、数字和无穷大的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429654/