javascript - 为什么以点结尾的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.'))
解决方案
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.
推荐阅读
- swift - Firebase:如果孩子小于 queryLimited 中的指定数字,则无法检索孩子
- excel - 如何在当前单元格上使用 HYPERLINK 和 VLOOKUP?
- python - Jupyter Notebook中的Pyathena找不到aws配置文件
- reactjs - 更改活动索引时如何使React Native tabview滚动回选项卡顶部
- r - 如何避免 geom_scatterpie() 函数中的重叠
- angular - typedef [Symbol.iterator] 的正确方法是什么?
- c# - 如何在静态方法中将 IConfiguration 对象注入 dotnet 核心项目?
- algorithm - 根据给定数组创建唯一对
- visual-studio - Visual Studio C/C++ Project with MASM code produces error `error A2008: syntax error : .`
- lua - 将 IR 代码列表转换为 Lua 数组/表