迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 中检查字符串是否为数字

作者:迹忆客 最近更新:2023/03/10 浏览次数:

编程语言中的数字是表示整数、浮点数等的数据类型。字符串表示所有字符而不仅仅是数值。字符串可以包含数值。

我们将在本文中检查给定的字符串是否为数字。

isNaN() 函数确定给定的值是数字还是非法数字(Not-a-Number)。该函数对于 NaN 值输出为 True,对于有效数值返回 False。

例子:

console.log(isNaN('195'))
console.log(isNaN('boo'))
console.log(isNaN('100px'))

输出:

false 
true
true

如果我们想创建一个对有效值返回 true 的函数,我们总是可以通过创建一个对 isNaN() 函数的输出求反的函数来实现。

function isNum(val){
  return !isNaN(val)
}
console.log(isNum('aaa'));          
console.log(isNum('13579'));        
console.log(isNum('-13'));

输出:

false
true
true

现在这个名为 isNum() 的函数将为有效的数值返回 true

+ 运算符返回字符串的数值,如果字符串不是纯数字字符,则返回 NaN

例如,

console.log(+'195')
console.log(+'boo')

输出:

195
NaN

parseInt() 函数解析一个字符串,然后返回一个整数。当无法从字符串中提取数字时,它返回 NaN。

例如,

console.log(parseInt('195'))
console.log(parseInt('boo'))

输出:

195
NaN

Number() 函数将参数转换为表示对象值的数字。如果无法将值转换为数字,则返回 NaN。

我们也可以将它与字符串一起使用来检查给定的字符串是否为数字。

例如,

console.log(Number('195'))
console.log(Number('boo'))

输出:

195
NaN

正则表达式是描述字符模式的对象。这些可用于搜索模式、对其进行更改、添加、删除等。

我们可以使用这样的模式来检查字符串是否包含数字。

例如,

function isNumeric(val) {
    return /^-?\d+$/.test(val);
}

console.log(isNumeric('aaa'));          
console.log(isNumeric('13579'));        
console.log(isNumeric('-13'));         

输出:

false
true
true

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便