版本

no-void

禁止使用 void 運算子

void 運算子接受一個運算元並回傳 undefinedvoid expression 會執行 expression 並回傳 undefined。它可以用來忽略 expression 可能產生的任何副作用。

使用 void 運算子的常見情況是取得「純」undefined 值,因為在 ES5 之前 undefined 變數是可變的。

// will always return undefined
(function(){
    return void 0;
})();

// will return 1 in ES3 and undefined in ES5+
(function(){
    undefined = 1;
    return undefined;
})();

// will throw TypeError in ES5+
(function(){
    'use strict';
    undefined = 1;
})();

另一個常見的情況是縮減程式碼,因為 void 0undefined 更短。

foo = void 0;
foo = undefined;

當與 IIFE (立即調用函式表達式) 一起使用時,void 可以用來強制將 function 關鍵字視為表達式而非宣告。

var foo = 1;
void function(){ foo = 1; }() // will assign foo a value of 1
+function(){ foo = 1; }() // same as above
function(){ foo = 1; }() // will throw SyntaxError

某些程式碼風格禁止 void 運算子,認為它不明顯且難以閱讀。

規則詳情

此規則旨在消除 void 運算子的使用。

此規則的錯誤程式碼範例

在遊樂場開啟
/*eslint no-void: "error"*/

void foo
void someFunction();

var foo = void bar();
function baz() {
    return void 0;
}

選項

此規則有一個物件選項

  • allowAsStatement 設定為 true 允許將 void 運算子用作陳述句 (預設值為 false)。

allowAsStatement

allowAsStatement 設定為 true 時,如果 void 運算子被用作陳述句,例如在變數賦值或函式回傳中未使用時,此規則不會產生錯誤。

{ "allowAsStatement": true }錯誤程式碼範例

在遊樂場開啟
/*eslint no-void: ["error", { "allowAsStatement": true }]*/

var foo = void bar();
function baz() {
    return void 0;
}

{ "allowAsStatement": true }正確程式碼範例

在遊樂場開啟
/*eslint no-void: ["error", { "allowAsStatement": true }]*/

void foo;
void someFunction();

何時不該使用

如果您有意使用 void 運算子,則可以停用此規則。

版本

此規則在 ESLint v0.8.0 中引入。

延伸閱讀

資源

變更語言