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

慎用Number.isNaN #101

Open
yubaoquan opened this issue Oct 31, 2023 · 0 comments
Open

慎用Number.isNaN #101

yubaoquan opened this issue Oct 31, 2023 · 0 comments

Comments

@yubaoquan
Copy link
Owner

yubaoquan commented Oct 31, 2023

在判断一个变量是不是数字时, 有时会使用 isNaN. 后来有了 Number.isNaN, 于是直接把 isNaN 替换成了 Number.isNaN. 这是有问题的.
isNaN 在判断时会先讲入参转换成数字, 如果转换失败, 那么就返回true
Number.isNaN 直接判断入参是不是 NaN 本身, 而不会执行本身

例如:

isNaN({}) // true
Number.isNaN({}) // false

isNaN(NaN) // true
Number.isNaN(NaN) // true

然而 isNaN 也存在问题. isNaN 会将空字符串转换成0, 将布尔值转换成 0 或 1. 这可能不是你想要的结果.

所以一般情况还是用 Number.isFinite 吧

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant