为什么 JavaScript 以不同方式处理字符串和数字之间的加号和减号运算符? [英] Why does JavaScript handle the plus and minus operators between strings and numbers differently?

查看:20
本文介绍了为什么 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 以不同方式处理字符串和数字之间的加号和减号运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆