js分号必写的场景

发布时间 2023-10-23 14:00:04作者: Cynthia娆墨旧染

 

一行开头是括号或者方括号的时候,末尾必须要加分号。

 

一、案例1

错误代码:

(() => {console.log(1)})()  // 注意这里没有分号
(() => {console.log(2)})()

正确代码:

(() => {console.log(1)})(); // 注意这里的分号
(() => {console.log(2)})()

 

 

二、案例2

错误代码:

const obj = new Object()
obj[Symbol.asyncIterator] = async function* () {
    yield 'a'
    yield 'b'
    yield 'c'
} // 注意这里没有分号
(async () => {
    for await (var x of obj) {
        console.log(x)
    }
})()

 

正确代码:

const obj = new Object()
obj[Symbol.asyncIterator] = async function* () {
    yield 'a'
    yield 'b'
    yield 'c'
}; // 注意这里的分号
(async () => {
    for await (var x of obj) {
        console.log(x)
    }
})()