You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《Eloquent JavaScript》中!Number.isNaN()的作用及相关代码解析问询

关于!Number.isNaN()作用的解答

嘿,我来给你掰扯清楚!Number.isNaN()到底干啥用的~

首先得拆成两部分理解:Number.isNaN()本身,加上前面的!逻辑非运算符。

1. 先搞懂Number.isNaN()

这个方法是用来**严格检测一个值是否就是NaN**的特殊方法,和全局的isNaN()有本质区别:

  • 全局isNaN()会先把传入的参数转换成数字,再判断是否是NaN;但Number.isNaN()只认真正的NaN值——只有当传入的值本身就是NaN(比如无效转换得到的结果),它才返回true。
  • 举个例子:Number.isNaN("abc")返回false(因为"abc"是字符串,不是NaN);但Number.isNaN(Number("abc"))返回true(因为Number("abc")会得到NaN)。

2. 再看!逻辑非运算符

这是个布尔值反转工具:把true变成false,把false变成true。

3. 合起来理解!Number.isNaN(theNumber)

它的作用就是:判断变量theNumber不是NaN,也就是它是一个有效的数字值。

结合你给出的代码片段来看:

let theNumber = Number(prompt("Pick a number"));
if (!Number.isNaN(theNumber)) {
console.log("Your number is the square root of " + theNumber * theNumber);
}

  • 如果用户输入能转换成有效数字的内容(比如"123"),Number(prompt(...))得到数字123,Number.isNaN(123)返回false,!反转后变成true,条件成立,就会执行输出语句。
  • 如果用户输入无效内容(比如"hello"或者直接点取消),Number(prompt(...))得到NaN,Number.isNaN(NaN)返回true,!反转后变成false,条件不成立,就不会执行输出。

内容的提问来源于stack exchange,提问作者j0ck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:58:52