Why does JavaScript handle the plus and minus operators between strings and numbers differently?(为什么 JavaScript 以不同方式处理字符串和数字之间的加号和减号运算符?)
问题描述
我不明白为什么 JavaScript 会这样工作.
I don't understand why JavaScript works this way.
console.log("1" + 1);
console.log("1" - 1);
第一行打印 11,第二行打印 0.为什么 JavaScript 将第一个作为字符串处理,将第二个作为数字处理?
The first line prints 11, and the second prints 0. Why does JavaScript handle the first as a String and the second as a number?
推荐答案
字符串连接是用 +
完成的,所以 Javascript 会将第一个数字 1 转换为字符串并连接1"和1"制作11".
String concatenation is done with +
so Javascript will convert the first numeric 1 to a string and concatenate "1" and "1" making "11".
你不能对字符串进行减法运算,所以 Javascript 将第二个1"转换为一个数字,并从 1 中减去 1,得到零.
You cannot perform subtraction on strings, so Javascript converts the second "1" to a number and subtracts 1 from 1, resulting in zero.
这篇关于为什么 JavaScript 以不同方式处理字符串和数字之间的加号和减号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 JavaScript 以不同方式处理字符串和数字之间的加号和减号运算符?


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