如何过滤掉javascripts过滤函数中的NaN

时间:2017-06-15 12:01:03

标签: javascript function filter

我需要帮助过滤掉NaN

var trimmer =[7, "ate", "", false, 9];

var filt = value=> value !==false && value!==''&& value!==undefined&&  
value!==null&&  value!==NaN;


trimmer.filter(filt);

//works for this->[7, "ate", "", false, 9];
//but not for [false, null, 0, NaN, undefined, ""];
//need help filtering out NaN

6 个答案:

答案 0 :(得分:2)

您可以改用isNan()功能。请点击this link查看更多示例。

答案 1 :(得分:2)

NaN是假的(假,未定义,null,"",0也是):

trimmer.filter(e=>e);

答案 2 :(得分:1)

NaN == NaN总是会给你错误。



var trimmer =[false, null, 0, NaN, undefined, ""];
var trimmer1 =[7, "ate", "", false, 9];

var filt = value=> value !==false && value!==''&& value!==undefined&&  
value!==null && value.toString() !== "NaN" && value !== 0;


console.log(trimmer.filter(filt));
console.log(trimmer1.filter(filt));
//works for this->[7, "ate", "", false, 9];
//but not for [false, null, 0, NaN, undefined, ""];
//need help filtering out NaN




答案 3 :(得分:1)

Rohodos简单更改值!= NaN!isNAN(value)

所以你的代码现在看起来像

var trimmer = [false, null, 0, NaN, undefined, ""];

var filt = value=> value !==false && value!==''&& value!==undefined&&value!==null&& !isNaN(value);

trimmer.filter(filt);

答案 4 :(得分:1)

Javascript将0视为false,因此将其过滤。需要检查变量的类型,如果它是数字返回true。



var trimmer = [false, null, 0, NaN, undefined, ""];

console.log(trimmer.filter(e=>e));




答案 5 :(得分:0)

如果你想特别过滤出NaN但留下其他假名值,那么这将有效:

import Vue from 'vue'
import App from './vue/App.vue'
import Grid from './vue/Grid.vue'
import PatternList from './vue/PatternList.vue'

Vue.component('grid', Grid);
Vue.component('pattern-list', PatternList);

new Vue({
  el: '#app',
  render: h => h(App)
});