Unary 一元
++/—
let a = false
a++ // 先把a转换成0再自增,a变成1,如果a是true,转换成1再自增
+/-
+可以将其他值转换为number,与Number()作用相同
-也可以转换,值会变负数
let s1 = "01";
let s2 = "1.1";
let s3 = "z";
let b = false;
let f = 1.1;
let o = {
valueOf() {
return -1;
}
};
s1 = +s1; // value becomes numeric 1
s2 = +s2; // value becomes numeric 1.1
s3 = +s3; // value becomes NaN
b = +b; // value becomes numeric 0
f = +f; // no change, still 1.1
o = +o; // value becomes numeric -1
Bitwise operator 位运算
All numbers in ECMAScript are stored in IEEE–754 64-bit format
~ 取反
& 与
| 或
^ 异或
<< 左移 >> 右移
Boolean operator
!
! 可以将任何值转换为布尔值,5个falsy值会变成true, 其他值会变成false
!! 用2个则相当于Boolean(),将任何值转换为对应的布尔值
console.log(!!"blue"); // true
console.log(!!0); // false
console.log(!!NaN); // false
console.log(!!""); // false
console.log(!!12345); // true
double ampersand ( && )
短路逻辑:
第一个值为真,则返回第二个值,
第一个值为假,则返回第一个值,第二个值忽略
double pipe ( || )
短路逻辑:
第一个值为真,则返回第一个值,第二个值忽略
第一个值为假,则返回第二个值
multiplicative operator
/%也会用Number()先将非数值转换为数值
asterisk ( )
slash ( / )
percent sign ( % )
Exponentiation Operator求幂
Math.pow(3,2) === 3**2
Math.sqrt(16) === 16 ** 0.5
add(+)
如果有一个是字符串,另一个也会转换为字符串
如果有不是字符串的会转换为字符串
"aaa" + null
// "aaanull"
"5" + 5
// "55"
subtract(-)
如果有不是数值的会转换为数值
5 - "5" // 0
5 - null // 5, null转为0
5 - undefined // NaN
Relational operators
less-than (<), greater-than (>), less-than-or-equal-to (<=), and greater-than-or-equal-to (>=)
/* 大写字母编码 < 小于小写字母 */
let result = "Brick" < "alphabet"; // true
/* 如果有一个数字,另一个也会转换成数字 */
let result = "23" < "3"; // true
let result = "23" < 3; // false
/* NaN和任何值比较都是false */
let result = "a" < 3; // false because "a" becomes NaN
Equality Operators
whether two variables are equivalent
null == undefined // true
"NaN" == NaN // false
5 == NaN // false
NaN == NaN // false
NaN != NaN // true
false == 0 // true
true == 1 // true
true == 2 // false
undefined == 0 // false
null == 0 // false
Number(null) === 0 // true
"5" == 5 // true
it is recommended to use identically equal(===) and not identically equal(!==)
Conditional Operator
let max = (num1 > num2) ? num1 : num2;
Assignment Operators
let num = 10;
num += 10;
Comma Operator
/* 用于声明 */
let num1 = 1, num2 = 2, num3 = 3;
/* 用于赋值,取最后一个值 */
let num = (5, 1, 4, 8, 0); // num becomes 0