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 以不同方式处理字符串和数字之间的加号和减号运算符?


- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01