比较运算符和相等运算符

15.1 使用===!==而不是==!=

eslint: eqeqeq

15.2 诸如if之类的条件语句的计算值会使用ToBoolean方法进行强制类型转换,通常遵循以下简单的规则:

  • Object => true
  • Undefined =>false
  • Null => false
  • Booleans => 对应的布尔值
  • Numbers => +0,-0,NaN是false,其他的是true
  • String -> 空字符串''是false,其他的是true
if ([0] && []) {
  // true
  // an array (even an empty one) is an object, objects will evaluate to true
}

15.3 布尔值可以使用简写,但是字符串和数字使用精确比较

// bad
if (isValid === true) {
  // ...
}

// good
if (isValid) {
  // ...
}

// bad
if (name) {
  // ...
}

// good
if (name !== '') {
  // ...
}

// bad
if (collection.length) {
  // ...
}

// good
if (collection.length > 0) {
  // ...
}

15.4 更多信息可以阅读Truth Equality and JavaScriptBy Angus Croll.

15.5 在casedefault条目里使用大括号来创建包含语句声明的块作用域.

eslint: no-case-declarations

为什么?语句声明在整个switch块里都是可见的,但只有当被赋值的时候才被初始化,这种情况是在它的case满足的时候。这样会在多个case语句都想定义同一个变量的时候引发问题。

// bad
switch (foo) {
  case 1:
    let x = 1;
    break;
  case 2:
    const y = 2;
    break;
  case 3:
    function f() {
      // ...
    }
    break;
  default:
    class C {}
}

// good
switch (foo) {
  case 1: {
    let x = 1;
    break;
  }
  case 2: {
    const y = 2;
    break;
  }
  case 3: {
    function f() {
      // ...
    }
    break;
  }
  case 4:
    bar();
    break;
  default: {
    class C {}
  }
}

15.6 三元条件运算符不要嵌套,且通常写在一行

eslint: no-nested-ternary

// bad
const foo = maybe1 > maybe2
  ? "bar"
  : value1 > value2 ? "baz" : null;

// split into 2 separated ternary expressions
const maybeNull = value1 > value2 ? 'baz' : null;

// better
const foo = maybe1 > maybe2
  ? 'bar'
  : maybeNull;

// best
const foo = maybe1 > maybe2 ? 'bar' : maybeNull;

15.6 避免不必要的三元条件运算符

eslint: no-unneeded-ternary

// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;

// good
const foo = a || b;
const bar = !!c;
const baz = !c;

15.8 当运算符混杂在一起的时候,用括号分开。当包含运算符的时候,不要把**%和它们弄混淆,也不要和+``-``*``/弄混

为什么?这样可以提升代码可读性并能清晰地表明开发者的意图

// bad
const foo = a && b < 0 || c > 0 || d + 1 === 0;

// bad
const bar = a ** b - 5 % d;

// bad
// one may be confused into thinking (a || b) && c
if (a || b && c) {
  return d;
}

// good
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);

// good
const bar = (a ** b) - (5 % d);

// good
if (a || (b && c)) {
  return d;
}

// good
const bar = a + b / c * d;

results matching ""

    No results matching ""