空语句用来表明没有语句,尽管 JavaScript 语法希望有语句。
;
空语句是一个分号(;),表示不会执行任何语句,即使 JavaScript 语法需要一个语句。 相反,当你需要多行语句,但 JavaScript 只允许一个时,可以使用语句块;语句块可以将多条语句合并为一个。
空语句有时与循环语句一起使用。以下示例使用空循环体:
var arr = [1, 2, 3];
// Assign all array values to 0
for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
console.log(arr)
// [0, 0, 0]
提示:在使用空语句的情况下专门写上注释是个不错的主意,因为不是很容易区分空语句和普通的分号。下面的示例可能不是故意加上分号的:
if (condition); // Caution, this "if" does nothing!
killTheUniverse() // So this gets always executed!!!
另一个例子:if...else
语句不带花括号({}
)。如果three
为true
, 不会发生任何事,four
不会执行,同时else
从句中的launchRocket()
函数也不会执行。
if (one)
doOne();
else if (two)
doTwo();
else if (three)
; // nothing here
else if (four)
doFour();
else
launchRocket();
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262) Empty statement |
Draft | |
ECMAScript 2015 (6th Edition, ECMA-262) Empty statement |
Standard | |
ECMAScript 5.1 (ECMA-262) Empty statement |
Standard | |
ECMAScript 3rd Edition (ECMA-262) Empty statement |
Standard | |
ECMAScript 1st Edition (ECMA-262) Empty statement |
Standard | Initial definition. |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Empty statement (; ) | Chrome Full support Yes | Edge Full support Yes | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Edge Mobile Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |