首页 > 编程语言 >javascript怎么判断字符串是否是数字

javascript怎么判断字符串是否是数字

时间:2022-08-26 18:34:23浏览次数:61  
标签:10 isNaN return 数字 javascript 是否是 Number 字符串

在javascript中,可以利用Number()函数和isNaN()函数来判断字符串是否是数字,语法“isNaN(Number("字符串",10)”;如果返回true,则该字符串不是数字,否则是数字。

javascript判断字符串是否是数字

通过Number()将字符串转化为数字的过程中,如果字符串中包含有非数字,那么将会返回NaN,参考下面代码

Number("Hello",10);//return NAN  

Number("110",10);//return 110 

Number("t2110",10);//return NAN  

Number("1f10g",10);//return NAN

 

 

 所以可以利用isNaN(),判断Number()的返回值是否为NaN来判断字符串是否是数字,如果返回true,则该字符串不为数字,否则为数字。

实现代码:

function f(a){

    if(isNaN(Number(a,10))){

        console.log("不是数字");

    }

    else{

        console.log("是数字");

    }

}

 

标签:10,isNaN,return,数字,javascript,是否是,Number,字符串
From: https://www.cnblogs.com/heibaiqi/p/16628787.html

相关文章

  • [Javascript] Prototype Pattern
    Source:https://javascriptpatterns.vercel.app/patterns/design-patterns/prototype-pattern Ifyouusefactorypatterntocreateobject:constcreateDog=(nam......
  • [Javascript] Factory pattern vs Class instance
    InJavaScript,thefactorypatternisn'tmuchmorethanafunctionthatreturnsanobjectwithoutusingthe new keyword. ES6arrowfunctions allowustocr......
  • Mysql 自定义随机字符串
    Mysql自定义随机字符串-搬砖工奶爸-博客园 https://www.cnblogs.com/--net/p/5784371.html 前几天在开发一个系统,需要用到随机字符串,但是mysql的库函数有没有直......
  • JavaScript变量及声明
    本文介绍了如何使用语法和示例声明和使用变量。变量用于将数据存储在JavaScript代码中。在JavaScript中使用变量之前,必须先对其进行声明。让我们看一下如何声明一个变量。......
  • JavaScript if else语句
    在编写程序时,可能需要从一组给定的路径中采用一个。在这种情况下,您需要使用条件语句,以使程序可以做出正确的决定并执行正确的操作。在JavaScript中,if-else语句用于在条件......
  • JavaScript switch语句
    除了if...else之外,JavaScript还有一个称为switch语句的功能。switch是一种条件语句,它将针对多种可能的情况评估表达式,并根据匹配的情况执行一个或多个代码块。switch语......
  • [Javascript] Singleton Pattern
    Source:https://javascriptpatterns.vercel.app/patterns/design-patterns/singleton-patternWiththeSingletonPattern,werestricttheinstantiationofcertainc......
  • springboot:@RequestBody 注解只能处理json格式的请求字符串吗?
    原来@RequestBody注解常用来处理content-type是application/json编码的内容,而不能用来处理application/x-www-form-urlcoded编码的内容。参考:https://blog.csdn.n......
  • 字符串题目
    KMP#include<iostream>#include<cstdio>#include<string>#include<cstring>usingnamespacestd;constintN=1e6+10;chara[N];//存字符串intne[N];//next数组......
  • Go语言 字符串切片转字符串
    []btye可以直接转换成string,但是如果有使用到split函数的需求,然后再str:=string([]string{}),go不支持这样的强转.参考博客:Golang字符切片转字符串不过go的......