js自動插入分號的規則

來源:互聯網
上載者:User

今天修改以前的js文法分析,重新看了下自動插入分號的規則。大概如下(ECMA262 v5,7.9):

1、當代碼解析過程中,發現一個不合規則的 token(此時稱該 token 為 offending token),在下列情況下,會自動插入分號:

  1. 該 token 前面有 分行符號
  2. 該 token 是 }

2、意外的結尾,此時會插入 1 個分號。

3、合法的 token 出現,但是該位置處於一些特殊語句環境(在 ECMA262 文法描述中,該位置叫 [no LineTerminator here]),並且該 token 前面有 分行符號,此時,會在上一個 token 後面插入分號。

PostfixExpression :
    LeftHandSideExpression [no LineTerminator here] ++
    LeftHandSideExpression [no LineTerminator here] --
ContinueStatement :
    continue [no LineTerminator here] ;
BreakStatement :
    break [no LineTerminator here] ;
ReturnStatement :
    return [no LineTerminator here] Expression ;
ThrowStatement :
    throw [no LineTerminator here] Expression ;

但是,如果插入的分號,是 空語句,或者 for 頭部的一部分時,不插入分號。

最後,儘管 js 引擎會自動插入分號,但最好不要利用該特性。而是,把分號寫全,做到一個不多一個不少。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.