您的位置:首页 > Web前端 > JavaScript

JavaScript 语句分号的必要性

2015-06-28 11:17 716 查看
Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes

the parser determine where the end of a statement occurs, as in the following examples:

var sum = a + b       //valid even without a semicolon - not recommended
var diff = a - b;     //valid - preferred


Even though a semicolon is not required at the end of statements, it is recommended to always

include one.
Including semicolons helps prevent errors of omission, such as not finishing what you

were typing, and allows developers to compress ECMAScript code by removing extra white space

(such compression causes syntax errors when lines do not end in a semicolon). Including semicolons

also improves performance in certain situations, because parsers try to correct syntax errors by

inserting semicolons where they appear to belong.

比如下面代码:

"use strict"

function f(a, b) {
    return
    a | b ;
}

console.log(f(2, 1));


输出:



所以,我们还是不要让解析器猜测我们的用意,毕竟解析器不是人工智能的:

正确写法:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: