使用JavaScript中的sort()将NaN推到数组的最后
我们有一个包含字符串和数字混合数据类型的数组,我们必须编写一个对数组进行排序的排序函数,以便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 ]
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短