Unary 一元

++/—

  1. let a = false
  2. a++ // 先把a转换成0再自增,a变成1,如果a是true,转换成1再自增

+/-

+可以将其他值转换为number,与Number()作用相同
-也可以转换,值会变负数

  1. let s1 = "01";
  2. let s2 = "1.1";
  3. let s3 = "z";
  4. let b = false;
  5. let f = 1.1;
  6. let o = {
  7. valueOf() {
  8. return -1;
  9. }
  10. };
  11. s1 = +s1; // value becomes numeric 1
  12. s2 = +s2; // value becomes numeric 1.1
  13. s3 = +s3; // value becomes NaN
  14. b = +b; // value becomes numeric 0
  15. f = +f; // no change, still 1.1
  16. 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(),将任何值转换为对应的布尔值

  1. console.log(!!"blue"); // true
  2. console.log(!!0); // false
  3. console.log(!!NaN); // false
  4. console.log(!!""); // false
  5. 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(+)
如果有一个是字符串,另一个也会转换为字符串
如果有不是字符串的会转换为字符串

  1. "aaa" + null
  2. // "aaanull"
  3. "5" + 5
  4. // "55"

subtract(-)
如果有不是数值的会转换为数值

  1. 5 - "5" // 0
  2. 5 - null // 5, null转为0
  3. 5 - undefined // NaN

Relational operators

less-than (<), greater-than (>), less-than-or-equal-to (<=), and greater-than-or-equal-to (>=)

  1. /* 大写字母编码 < 小于小写字母 */
  2. let result = "Brick" < "alphabet"; // true
  3. /* 如果有一个数字,另一个也会转换成数字 */
  4. let result = "23" < "3"; // true
  5. let result = "23" < 3; // false
  6. /* NaN和任何值比较都是false */
  7. let result = "a" < 3; // false because "a" becomes NaN

Equality Operators

whether two variables are equivalent

  1. null == undefined // true
  2. "NaN" == NaN // false
  3. 5 == NaN // false
  4. NaN == NaN // false
  5. NaN != NaN // true
  6. false == 0 // true
  7. true == 1 // true
  8. true == 2 // false
  9. undefined == 0 // false
  10. null == 0 // false
  11. Number(null) === 0 // true
  12. "5" == 5 // true

it is recommended to use identically equal(===) and not identically equal(!==)

Conditional Operator

  1. let max = (num1 > num2) ? num1 : num2;

Assignment Operators

  1. let num = 10;
  2. num += 10;

Comma Operator

  1. /* 用于声明 */
  2. let num1 = 1, num2 = 2, num3 = 3;
  3. /* 用于赋值,取最后一个值 */
  4. let num = (5, 1, 4, 8, 0); // num becomes 0