在 JavaScript 中使用 sort() 将 NaN 推到数组的最后

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/24 19:56:17

我们有一个包含字符串和数字混合数据类型的数组,我们必须编写一个排序函数对数组进行排序,以便 NaN 值始终位于底部。

数组应该在前面包含所有有效数字,然后是字符串文字,然后是 NaN。

其代码为 −

const arr = [344, 'gfd', NaN, '', 15, 'f',176, NaN, 736, NaN, 872, 859,
'string', 13, 'new', NaN, 75];
const sorter = (a, b) => {
   if(a !== a){
      return 1;
   }else if(b !== b){
      return -1;
   }
   return typeof a === 'number' ? -1 : 1;
};
arr.sort(sorter);
console.log(arr);

输出

控制台中的输出 −

[
   75, 13, 859,
   872, 736, 176,
   15, 344, 'gfd',
   '', 'f', 'string',
   'new', NaN, NaN,
   NaN, NaN
]

相关文章


有用资源