How to add two strings as if they were numbers?(如何添加两个字符串,就好像它们是数字一样?)
问题描述
我有两个只包含数字的字符串:
I have two strings which contain only numbers:
var num1 = '20',
num2 = '30.5';
我原以为我可以将它们加在一起,但它们被串联起来了:
I would have expected that I could add them together, but they are being concatenated instead:
num1 + num2; // = '2030.5'
如何强制将这些字符串视为数字?
How can I force these strings to be treated as numbers?
推荐答案
我会先使用一元加号运算符将它们转换为数字.
I would use the unary plus operator to convert them to numbers first.
+num1 + +num2;
这篇关于如何添加两个字符串,就好像它们是数字一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何添加两个字符串,就好像它们是数字一样?


基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01