分号

21.1 使用分号

为什么?当javascript遇到没有分号的换行符时,它使用一种称为自动分号插入(ASI)的规则来确定是否应将该换行符视为语句的结尾,如果这个规则认为需要的话,就会在换行符前插入分号。ASI包含一些古怪的行为,因此,如果javascript错误地解释了你的换行符,你的代码将会中断。随着一些新功能的加入,这些规则将变得更加复杂。明确地终止你的陈述和配置你的linter防止分号缺失将有助于防止遇到问题。

// bad - 引发异常
const luke = {}
const leia = {}
[luke, leia].forEach(jedi => jedi.father = 'vader')

// bad - 引发异常
const reaction = "No! That's impossible!"
(async function meanwhileOnTheFalcon(){
  // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
  // ...
}())

// bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!
// bad - 会返回`undefined`而不是下一行的值
function foo() {
  return
    'search your feelings, you know it to be foo'
}

// good
const luke = {};
const leia = {};
[luke, leia].forEach((jedi) => {
  jedi.father = 'vader';
});

// good
const reaction = "No! That's impossible!";
(async function meanwhileOnTheFalcon(){
  // handle `leia`, `lando`, `chewie`, `r2`, `c3p0`
  // ...
}());

// good
function foo() {
  return 'search your feelings, you know it to be foo';
}

results matching ""

    No results matching ""