empty

空语句用来表明没有语句,尽管 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 语句不带花括号({})。如果threetrue, 不会发生任何事,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.

浏览器兼容

Update compatibility data on GitHub
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Empty statement (;) Chrome Full support 3 Edge Full support 12 Firefox Full support 1 IE Full support 3 Opera Full support Yes Safari Full support Yes WebView Android Full support 1 Chrome Android Full support 18 Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 1.0 nodejs Full support Yes

Legend

Full support  
Full support

相关链接