Home Web Front-end JS Tutorial How to determine whether it is a number in javascript

How to determine whether it is a number in javascript

Apr 07, 2021 pm 02:01 PM
javascript number

javascript判断是否为数字的方法:1、使用isNaN()函数,语法格式“isNaN(value)”,可以检查其参数value是否为非数字值;2、使用test()函数配合正则表达式来判断;3、利用parseFloat()函数来判断。

How to determine whether it is a number in javascript

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

1.使用isNaN()函数

isNaN()的缺点就在于 null、空格以及空串会被按照0来处理

NaN: Not a Number

/**
*判断是否是数字
*
**/

function isRealNum(val){
    // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除,
    
  if(val === "" || val ==null){
        return false;
  }
   if(!isNaN(val)){    
  //对于空数组和只有一个数值成员的数组或全是数字组成的字符串,isNaN返回false,例如:'123'、[]、[2]、['123'],isNaN返回false,
   //所以如果不需要val包含这些特殊情况,则这个判断改写为if(!isNaN(val) && typeof val === 'number' )
    return true; 
  }

 else{ 
    return false; 
  } 
}
Copy after login

isNaN()函数来判断一个值是数字的最正确的方法就是:

// true:数值型的,false:非数值型
  function myIsNaN(value) {
    return typeof value === 'number' && !isNaN(value);
  }
Copy after login

isNaN()详解

对于空数组和只有一个数值成员的数组,isNaN返回false

isNaN([]) // false
isNaN([123]) // false
isNaN(['123']) // false
Copy after login

上面代码之所以返回false,原因是这些数组能被Number函数转成数值,请参见《数据类型转换》一章。

因此,使用isNaN之前,最好判断一下数据类型。

function myIsNaN(value) {
  return typeof value === 'number' && !isNaN(value);
}
Copy after login

2.使用正则表达式 

(1)、校验只要是数字(包含正负整数,0以及正负浮点数)就返回true

/**
* 校验只要是数字(包含正负整数,0以及正负浮点数)就返回true
**/

function isNumber(val){

    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val) && regNeg.test(val)){
        return true;
    }else{
        return false;
    }

}
Copy after login

(2)、校验正负正数就返回true

/**
* 校验正负正数就返回true
**/

function isIntNum(val){
    var regPos = / ^\d+$/; // 非负整数 
    var regNeg = /^\-[1-9][0-9]*$/; // 负整数
    if(regPos.test(val) && regNeg.test(val)){
        return true;
    }else{
        return false;
    } 
}
Copy after login

常用正则:

"^\\d+$"             //非负整数(正整数 + 0) 
"^[0-9]*[1-9][0-9]*$"     //正整数 
"^((-\\d+)|(0+))$"       //非正整数(负整数 + 0) 
"^-[0-9]*[1-9][0-9]*$"    //负整数 
"^-?\\d+$"            //整数 
"^\\d+("            //非负浮点数(正浮点数 + 0) 
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"    //正浮点数 
"^((-\\d+("           //非正浮点数(负浮点数 + 0) 
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"    //负浮点数 
"^(-?\\d+)("         //浮点数
Copy after login

3.使用parseFloat()函数

/**
* 验证数据 是数字:返回true;不是数字:返回false
**/

function Number(val) {
  if (parseFloat(val).toString() == "NaN") {
    
    return false;
  } else {
    return true;
  }
}

//isNaN(val)不能判断空串或一个空格
//如果是一个空串、空格或null,而isNaN是做为数字0进行处理的,而parseInt与parseFloat是返回一个错误消息,这个isNaN检查不严密而导致的。
Copy after login

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to determine whether it is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Realme GT Neo6 is scheduled to be released on May 9th! The first AI digital human conference in the computer industry Realme GT Neo6 is scheduled to be released on May 9th! The first AI digital human conference in the computer industry May 08, 2024 pm 12:49 PM

On May 7, our mobile phone manufacturer officially announced that our company’s GTNeo6 launch conference is scheduled for May 9. GTNoe6 is positioned as a "performance storm", aiming to stir up the mid-range machine situation. In addition, this conference will also be the first AI digital human conference in the mobile phone industry. At that time, Realme Vice President, Global Marketing President, and China President Xu Qi will appear at the press conference in the form of a digital human. Digital man Xu Qi According to the official introduction, Realme GTNoe6, codenamed "Hurricane", is faster and stronger. It will challenge the strongest third-generation Snapdragon 8s flagship and the strongest product in its class. Recently, the Realme GTNeo6 was found to be directly on the e-commerce platform. Some core configurations were exposed, showing that the machine is not only equipped with a Snapdragon 8s processor, but also supports 120W flash charging.

How to convert string to number in Golang How to convert string to number in Golang Jan 16, 2024 am 08:20 AM

How to convert strings to numbers in Golang In Golang, we often need to convert strings to numbers to perform some calculation operations. The process of converting strings to numbers is relatively simple and mainly relies on the strconv package in the Golang standard library. This article will introduce in detail how to use the strconv package to convert strings to numbers and give some specific code examples. Converting a string to an integer To convert a string to an integer, you can use the Atoi function from the strconv package. Ato

JavaScript and WebSocket: Building an efficient real-time search engine JavaScript and WebSocket: Building an efficient real-time search engine Dec 17, 2023 pm 10:13 PM

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

See all articles