首页 > 解决方案 > 为什么以点结尾的javascript Number会返回一个数字,但是在正则表达式函数中它会失败

问题描述

任何以点结尾的整数都会返回 javascript 控制台中的数字。(十进制数字除外)

喜欢> 1.回报1。添加>1+1.也有效。我不明白为什么

typeof(1) // 'number'
typeof(1.) //'number'

但是,当我在函数中放入相同的数字时,正则表达式测试会给出错误的输出。

IE,

const regex = /^\d+$/ //checks if there is a number inside a string
regex.test('1') // true
regex.test(1)   //true
regex.test('1.') // false

我的解决方法很简单regex.test(Number('1.'))

标签: javascriptregex

解决方案


JavaScript has a single type for all numbers: it treats all of them as floating-point numbers. However, the dot is not displayed if there are no digits after the decimal point:

5.000 = 5

Also, \d matches a digit, not a number.


推荐阅读