原文:https://zh.javascript.info/operators
怕看了就忘记,决定敲一遍&抄一边
1.拼接变量
a.都是字符串
let s = "my" + "string";
alert(s); // mystring
只要任一变量是字符串,那么其它变量也会转化为字符串b.
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21
运算符的运算方向是由左至右如果是多变量运算,前几个是Num,最后是字符串,则会先做运算再拼接(
)
alert(2 + 2 + '1' ); // "41" 而不是 "221"
p:除了+运算符外其他-、*、%不具备这特性,其他运算符会进行字符串转数字运算,如
alert( 2 - '1' ); // 1
alert( '6' / '2' ); // 3
2.将字符转换成Num
a.在单个Num类型前添加+是没有用的
// 对数字无效
let x = 1;
alert( +x ); // 1
let y = -2;
alert( +y ); // -2
b.如果变量是非数字,+会将其转化为数字
// 转化非数字
alert( +true ); // 1
alert( +"" ); // 0
let apples = "2";
let oranges = "3";
// 在二元运算符加号起作用之前,所有的值都转为数字
alert( +apples + +oranges ); // 5
// 上面等同于下面这语句,但下面这个复杂一些
alert( Number(apples) + Number(oranges) ); // 5