17

JavaScript判断字符串是否为数字类型:Number.isInteger、isNaN、正则表达式比较

 4 years ago
source link: http://ourjs.com/detail/k96ccn5eixcg
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript中有Number.isInteger可以判断一个字符串是否为整数。不过目前JS没有内置的函数来判断一个数字是否为包含小数的数字:

Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true

Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false

Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false

下面简介几种判断的简单方法:

方法1: 正则表达式

用正则是比较保险,缺点是性能略差

function isNumber(val) {
  // negative or positive
  return /^[-]?[\.\d]+$/.test(val);
}

方法2: Number类型转换

思路是先转换成数字,再看看是不是NaN

function isNumber(val) {
  return !isNaN(Number(val))
}

方法3: 直接用isNaN

根据方法2变种过来,其实可以先不进行类型转换,直接用isNaN即可:

function isNumber(val) {
  return !isNaN(val);
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK