Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

什么是NaN?以及如何检查值是否为NaN? #283

Open
Sogrey opened this issue Sep 10, 2020 · 0 comments
Open

什么是NaN?以及如何检查值是否为NaN? #283

Sogrey opened this issue Sep 10, 2020 · 0 comments

Comments

@Sogrey
Copy link
Owner

Sogrey commented Sep 10, 2020

NaN表示**“非数字”**是 JS 中的一个值,该值是将数字转换或执行为非数字值的运算结果,因此结果为NaN

let a;

console.log(parseInt('abc')); // NaN
console.log(parseInt(null)); // NaN
console.log(parseInt(undefined)); // NaN
console.log(parseInt(++a)); // NaN
console.log(parseInt({} * 10)); // NaN
console.log(parseInt('abc' - 2)); // NaN
console.log(parseInt(0 / 0)); // NaN
console.log(parseInt('10a' * 10)); // NaN

JS 有一个内置的isNaN方法,用于测试值是否为isNaN值,但是这个函数有一个奇怪的行为。

console.log(isNaN()); // true
console.log(isNaN(undefined)); // true
console.log(isNaN({})); // true
console.log(isNaN(String('a'))); // true
console.log(isNaN(() => { })); // true

所有这些console.log语句都返回true,即使我们传递的值不是NaN

ES6中,建议使用Number.isNaN方法,因为它确实会检查该值(如果确实是NaN),或者我们可以使自己的辅助函数检查此问题,因为在 JS 中,NaN是唯一的值,它不等于自己。

function checkIfNaN(value) {
  return value !== value;
}
@Sogrey Sogrey added this to javascript in Web面经题 Sep 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Web面经题
javascript
Development

No branches or pull requests

1 participant