为什么NaN(“"“)(带空格的字符串)等于false? [英] Why does isNaN(" ") (string with spaces) equal false?

查看:81
本文介绍了为什么NaN(“"“)(带空格的字符串)等于false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,为什么isNaN(" ")评估为false,而isNaN(" x")评估为true?

In JavaScript, why does isNaN(" ") evaluate to false, but isNaN(" x") evaluate to true?

我正在对文本输入字段执行数字运算,并且正在检查该字段是null""还是NaN.当有人在该字段中输入少量空格时,我的验证在这三个字段上都失败了,我困惑为什么它不能通过isNaN检查.

I’m performing numerical operations on a text input field, and I’m 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.然后结果应为NAN.

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.

这篇关于为什么NaN(“"“)(带空格的字符串)等于false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆