本文介绍了为什么isNaN(“"”)等于false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题(我希望!)。在JS中,为什么 isNaN()评估为false,但 isNaN(x)评估为true ?

I have a quick question (I hope!). In JS, why does isNaN(" ") evaluate to false, but isNaN(" x") evaluate to true?

我正在对文本输入字段执行数值运算,并检查字段是否为空,或NaN。当有人在场中键入少量空格时,我的验证在所有三个空格中都失败了,我很困惑为什么它超过了isNAN检查。

I'm performing numerical operations on a text input field, and am checking if the field is null, "", or NaN. When someone types a handful of spaces into the field, my validation fails on all three, and I'm confused as to why it gets past the isNAN check.

谢谢!

推荐答案

JavaScript将空字符串解释为0,然后无法通过isNAN测试。你可以先在字符串上使用parseInt,它不会将空字符串转换为0.结果应该是失败的isNAN。

JavaScript interprets an empty string as a 0, which then fails the isNAN test. You can use parseInt on the string first which won't convert the empty string to 0. The result should then fail isNAN.

这篇关于为什么isNaN(“"”)等于false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-05 10:49