最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Remove NaN value, javascript - Stack Overflow

matteradmin4PV0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 4

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; };
}

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');
Post a comment

comment list (0)

  1. No comments so far