Reputation: 4234
Index 28:
How do I remove this "NaN" value. Cant use isNaN
because I want strings and numbers. But not NaN
Tried:
typeof value === 'undefined'
value == null
No success.
Upvotes: 1
Views: 2630
Reputation: 18113
you can use typeof
(to check that's a number) in combination with isNaN
Note that typeof NaN
returns "number"
typeof x === "number" && isNaN(x)
Another solution is to use Number.isNaN which will not trying to convert the parameter into a number. So it will return true
only when the parameter is NaN
Upvotes: 4
Reputation: 1012
I’ve seen this comparison check, not sure if you could make it work for you.
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
Upvotes: 0
Reputation: 85767
You can test for NaN
specifically by using Number.isNaN
, which is subtly different from plain isNaN
: It only returns true if its argument is a number (whose value is NaN). In other words, it won't try to coerce strings and other values to numbers.
Demo:
const values = [
12,
NaN,
"hello",
{ foo: "bar" },
NaN,
null,
undefined,
-3.14,
];
const filtered = values.filter(x => !Number.isNaN(x));
console.log(filtered);
Number.isNaN
is new in ECMAScript 6. It is supported by every browser except Internet Explorer. In case you need to support IE, here's a simple workaround:
if (!Number.isNaN) {
Number.isNaN = function (x) { return x !== x; };
}
Upvotes: 4
Reputation: 1545
You should be able to use Number.isNaN
console.log([1, "foo", NaN, "bar"].filter((x) => !Number.isNaN(x)))
Upvotes: 0