重学前端学习笔记(二十九)--JavaScript中要不要加分号?

笔记说明

重学前端是程劭非(winter)【前手机淘宝前端负责人】在极客时间开的一个专栏,天天10分钟,重构你的前端知识体系,笔者主要整理学习过程的一些要点笔记以及感悟,完整的能够加入winter的专栏学习【原文有winter的语音】,若有侵权请联系我,邮箱:kaimo313@foxmail.com。前端

1、自动插入分号规则

1.一、三条规则

  • 要有换行符,且下一个符号是不符合语法的,那么就尝试插入分号。
  • 有换行符,且语法中规定此处不能有换行符,那么就自动插入分号。
  • 源代码结束处,不能造成完整的脚本或者模块结构,那么就自动插入分号。

1.二、例子

//第一行的结尾处有换行符,接下来 void 关键字接在 1 以后是不合法的,根据第一条规则,会在 void 前插入换行符。
let a = 1
void function(a){
    console.log(a);
}(a);
复制代码
// 根据no LineTerminator here 规则, a 的后面就要插入一个分号。
var a = 1, b = 1, c = 1;
a
++
b
++
c
// a ==> 1 b,c ==> 2
复制代码

1.三、例子 no LineTerminator here 规则展现

UpdateExpression[Yield, Await]:
    LeftHandSideExpression[?Yield, ?Await]
    LeftHandSideExpression[?Yield, ?Await][no LineTerminator here]++
    LeftHandSideExpression[?Yield, ?Await][no LineTerminator here]--
    ++UnaryExpression[?Yield, ?Await]
    --UnaryExpression[?Yield, ?Await]
复制代码

1.四、IIFE(当即执行的函数表达式)

(function(){
    console.log(1);
})()
(function(){
    console.log(2);
})()

// 不加分号,输出结果
// 1 Uncaught TypeError: (intermediate value)(...) is not a function

(function(){
    console.log(1);
})();
(function(){
    console.log(2);
})()

// 加分号,输出结果
// 1 2

// 关于这个问题,遇到过,当时排查几十分钟 _(:3」∠)_ , 因为我以前的是有换行,还有注释,当时一直不理解,相似下面这样
(function(){
    console.log(1);
})()

// 处理。。。业务
(function(){
    console.log(2);
})()
复制代码

1.五、带换行符的注释

// 带换行符的注释也被认为是有换行符,return 也有 [no LineTerminator here] 规则的要求,这里会自动插入分号
function f(){
    return/* This is a return value. */1;
}
f();

// undefined
复制代码

2、no LineTerminator here 规则

no LineTerminator here 规则表示它所在的结构中的这一位置不能插入换行符。正则表达式

no LineTerminator here 规则

2.一、带标签的 continue 语句

// 不能在 continue 后插入换行。
outer:for(var j = 0; j < 10; j++)
    for(var i = 0; i < j; i++)
        continue /*no LineTerminator here*/ outter
复制代码

2.二、return

function f(){
    return /*no LineTerminator here*/1;
}
复制代码

2.三、后自增、后自减运算符

i/*no LineTerminator here*/++
i/*no LineTerminator here*/--
复制代码

2.四、throw 和 Exception 之间

throw/*no LineTerminator here*/new Exception("error")
复制代码

2.五、async 关键字

// 后面都不能插入换行符
async/*no LineTerminator here*/function f(){

}
const f = async/*no LineTerminator here*/x => x*x
复制代码

2.六、箭头函数

// 箭头函数的箭头前,也不能插入换行
const f = x/*no LineTerminator here*/=> x*x
复制代码

2.七、yield

// yield 以后,不能插入换行
function *g(){
    var i = 0;
    while(true)
        yield/*no LineTerminator here*/i++;
}
复制代码

3、不写分号须要注意的状况

3.一、以括号开头的语句

(function(a){
    console.log(a);
})()/* 这里没有被自动插入分号 */
(function(a){
    console.log(a);
})()
复制代码

3.二、以数组开头的语句

var a = [[]]/* 这里没有被自动插入分号 */
[3, 2, 1, 0].forEach(e => console.log(e))
复制代码

3.三、以正则表达式开头的语句

// 正则边除号
var x = 1, g = {test:()=>0}, b = 1/* 这里没有被自动插入分号 */
/(a)/g.test("abc")
console.log(RegExp.$1)
复制代码

3.四、以 Template 开头的语句

// 没有自动插入分号,函数 f 被认为跟 Template 一体的,会被执行。
var f = function(){
  return "";
}
var g = f/* 这里没有被自动插入分号 */
`Template`.match(/(a)/);
console.log(RegExp.$1)
复制代码

我的总结

表示跟winter同样,也是标分号党。。。数组

相关文章
相关标签/搜索