控制语句

17.1 如果你的控制语句(if,while等)太长或超过最大行长度,每个条件可以被放入一个新行,逻辑运算符放在行首。

为什么?把连接符放在行首能够是连接符对其而且这样跟链式方法类似。这样也能通过提升复杂逻辑的可视化来提升代码可读性

// bad
if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) {
  thing1();
}

// bad
if (foo === 123 &&
  bar === 'abc') {
  thing1();
}

// bad
if (foo === 123
  && bar === 'abc') {
  thing1();
}

// bad
if (
  foo === 123 &&
  bar === 'abc'
) {
  thing1();
}

// good
if (
  foo === 123
  && bar === 'abc'
) {
  thing1();
}

// good
if (
  (foo === 123 || bar === "abc")
  && doesItLookGoodWhenItBecomesThatLong()
  && isThisReallyHappening()
) {
  thing1();
}

// good
if (foo === 123 && bar === 'abc') {
  thing1();
}

results matching ""

    No results matching ""