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


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01