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

如何编写isNumber函数 接收val参数判断值是否为number类型

isNumber 函数实现

要实现判断传入值是否为 JavaScript 原始 number 类型的isNumber函数,匹配给出的示例输入输出规则,可参考以下方案。

最简实现(覆盖所有列出示例场景)

直接用原生typeof运算符做类型判断即可,该运算符对原始 number 类型会固定返回'number',不会和布尔值、null、字符串类型的值混淆:

function isNumber(val) {
  return typeof val === 'number';
}

对应示例的运行结果完全符合预期:

isNumber(1)     // true
isNumber(0)     // true
isNumber(true)  // false
isNumber(null)  // false
isNumber('1')   // false

可选扩展:排除特殊数字值

上述基础实现会将 JS 中属于 number 类型的特殊值也判定为true,包括NaN、Infinity、-Infinity。如果需要排除这些非有效数字的特殊值,只判定常规有效数字,可以加一层校验逻辑:

function isNumber(val) {
  return typeof val === 'number' && Number.isFinite(val);
}

这个版本下调用isNumber(NaN)、isNumber(Infinity)都会返回false,可根据实际业务需求选择对应实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:27:41