• 技术文章 >web前端 >js教程

    Javascript分号规则的知识介绍(附示例)

    不言不言2019-03-25 14:21:03转载804
    本篇文章给大家带来的内容是关于Javascript分号规则的知识介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

    花点时间搞清楚JS中的分号规则吧~~~不管你喜欢结尾带分号或省略分号的模式

    分号允许的场景

    分号一般允许出现在大部分语句(statement)的末尾,比如 do-while statement , var statements, expression statements , continue , return , break statement, throw, debugger 等

    栗子:

    do Statement while ( Expression ) ;
    
    4+4;
    
    f();
    
    debugger;

    仅有一个分号 ; 可以表示空语句——在JS中合法,比如 ;;; 可解析为三个空语句(empty statement)

    空语句可用于辅助产生语法合法的解析结果,如:

    while(1);

    如果没有末尾的分号,将会产生解析错误 —— 条件循环后必须跟随一个语句

    分号还会出现在 for 循环 for ( Expression ; Expression ; Expression ) Statement 中

    最后,分号还会出现在 字符串 或 正则表达式中 —— 表示分号本身

    分号可以省略的场景

    有些场景下分号可以省略,解析器在解析语句时会根据需要自动插入分号,大概流程可以这样理解:

    书写省略 => 解析器解析时发现缺少时会无法正确解析 => 自动添加分号

    so 需要明确能自动插入分号的场景,并明确不会自动插入分号且会引起解析错误的情况

    规则1:当下一个 token (offending token) 和当前解析的 token (previous token) 无法组成合法语句,且满足以下一个或多个条件时,将会在 offending token 前插入一个分号:

    还要考虑一种优先级更高的条件:如果插入的分号会被解析为一个空语句,或是 for 语句的头部两个分号之一,这时不会插入分号(除了 do-while 语句的终止分号外)

    规则2:当解析到达源代码文件 (input stream) 的末尾时,将自动添加一个分号标识解析结束

    规则3:符合 restricted production 语法的语句 —— 比较难翻译,看不懂的可以直接看栗子,这种情况主要描述的是:不应该出现换行符的地方出现换行符导致插入分号引起原语句含义变化

    同时满足以下条件,将在 offending token 前自动插入一个分号:

    其中 restricted production 包括且只有以下:

    UpdateExpression[Yield, Await]:
      LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++
      LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] --
    
    ContinueStatement[Yield, Await]:
      continue;
      continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await];
    
    BreakStatement[Yield, Await]:
      break;
      break  [no LineTerminator here]  LabelIdentifier[?Yield, ?Await];
    
    ReturnStatement[Yield, Await]:
      return;
      return  [no LineTerminator here]  Expression  [+In, ?Yield, ?Await];
    
    ThrowStatement[Yield, Await]:
      throw [no LineTerminator here] Expression [+In, ?Yield, ?Await];
    
    ArrowFunction[In, Yield, Await]:
      ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In]
    
    YieldExpression[In, Await]:
      yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await]
      yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await]

    简单总结:

    使用 a++ 语句时,变量和 ++ 必须在同一行,否则会在 ++ 前插入分号导致语义不同

    return throw yield continue break 后如果紧跟着换行,将会自动添加分号

    箭头函数的 => 之前不应该有换行符

    栗子 & 可能不符合预期的情况

    符合预期情况

    // 相当于 42;"hello"
    42
    "hello"
    
    // offending token 是 }
    if(x){y()}
    
    // previous token 是 ) 且插入分号是 do while 语句的结束
    var a = 1
    do {a++} while(a<100)
    console.log(a)
    
    //  不会解析成 b++ 因为 b和++之间存在换行符,会在 b 之后自动插入分号
    a = b
    ++c

    可能不符合预期的情况

    const hey = 'hey'
    const you = 'hey'
    const heyYou = hey + ' ' + you
    
    ['h', 'e', 'y'].forEach((letter) => console.log(letter))

    会收到错误 Uncaught TypeError: Cannot read property 'forEach' of undefined , 因为 you 和 ['h', 'e', 'y'] 的连接能命中合法语法,故它们之间不会自动插入分号 —— 与预期不一致,JS尝试将代码解析为:

    const hey = 'hey';
    const you = 'hey';
    const heyYou = hey + ' ' + you['h', 'e', 'y'].forEach((letter) => console.log(letter))

    再看一种情况:

    const a = 1
    const b = 2
    const c = a + b
    (a + b).toString()

    会引发 TypeError: b is not a function 报错,因为会被解释为:

    const a = 1
    const b = 2
    const c = a + b(a + b).toString()

    除了 do while 语句外,不会有插入分号作为空语句的其他情况,或作为 for 语句头部的两个必要分号 :

    if (a > b)
    else c = d
    
    for (a; b
    )

    以上均不是合法的 JS 语句,并且会引起报错

    故以下栗子中的每一个分号都不能省略!!

    // for循环没有循环体的情况,每一个分号都不能省略
    for (node=getNode();
         node.parent;
         node=node.parent) ;

    再看一个带详细注释的例子:

    var         // 这一行不会插入分号 ,因为 下一行的代码不会破坏当前行的代码  
        a = 1   // 这一行会插入分号   
    let b = 2   
    
    // 再比如这种情况,你的原意可能是定义 `a` 变量,再执行 `(a + 3).toString()`,
    // 但是其实 JavaScript 解析器解析成了,`var a = 2(a + 3).toString()`,
    // 这时会抛出错误 Uncaught TypeError: 2 is not a function
    var a = 2
    (a + 3).toString()
    
    // 同理,下面的代码会被解释为 `a = b(function(){...})()`
    a = b
    (function(){
    ...
    })()

    以上都是未能命中规则1而未插入分号导致解析与预期不符合的情况

    看一个基于规则3的例子:

    (() => {
      return
      {
        color: 'white'
      }
    })()

    预期是返回一个包含 color 属性的对象,但事实上 return 后会被插入一个分号,而导致最终返回 undefined,可以通过在 return 后立刻放置花括号 { :

    (() => {
      return {
        color: 'white'
      }
    })()

    省略分号的最佳实践

    不要使用以下单个字符 ( [ / + - 开始一行 , 会极有可能和上一行语句合在一起被解析( ++ 和 -- 不符合单个 +、- 字符)

    注意 return break throw continue 语句,如果需要跟随参数或表达式,把它添加到和这些语句同一行,针对 return 返回内容较多的情况 (大对象,柯里化调用,多行字符串等),可以参考规则1,避免命中该规则而引起非预期的分号插入,比如:

    return obj.method('abc')
              .method('xyz')
              .method('pqr')
     
    return "a long string\n"
         + "continued across\n"
         + "several lines"
     
    totalArea = rect_a.height * rect_a.width
              + rect_b.height * rect_b.width
              + circ.radius * circ.radius * Math.PI
    后缀运算符 ++ -- 需要和操作变量在同一行使用

    当然大部分工程化情况下,我们最终会配合Eslint使用带分号或省略分号规范~~~

    本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

    以上就是Javascript分号规则的知识介绍(附示例)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除
    专题推荐:javascript 语法
    上一篇:apply() 和 call() 方法有什么作用? 下一篇:JavaScript中AMD和ES6模块导入导出的比较(代码示例)
    大前端线上培训班

    相关文章推荐

    • javascript声明提升的介绍(附示例)• JavaScript数据类型的介绍• JavaScript中的var和let的区别(代码示例)• javascript中对象的介绍(附代码)• JavaScript实现递归算法的方法介绍• 如何更新JavaScript中的cookie?(代码示例)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网