admin管理员组文章数量:1435859
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.
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.
Share Improve this question edited May 10, 2019 at 22:29 melpomene 85.9k8 gold badges95 silver badges154 bronze badges asked May 10, 2019 at 22:05 JoeJoe 4,27432 gold badges106 silver badges180 bronze badges4 Answers
Reset to default 4You 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; };
}
you can use typeof
(to check that's a number) in bination 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
You should be able to use Number.isNaN
console.log([1, "foo", NaN, "bar"].filter((x) => !Number.isNaN(x)))
I’ve seen this parison check, not sure if you could make it work for you.
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
本文标签: Remove NaN valueJavaScriptStack Overflow
版权声明:本文标题:Remove NaN value, javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745242874a2649421.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论