
no-void
禁用 void
運算子
❄️ Frozen
此規則目前為凍結狀態,且不接受功能請求。
void
運算子接受一個運算元並回傳 undefined
:void 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 0
比 undefined
更短
foo = void 0;
foo = undefined;
當與 IIFE (立即調用函式表達式) 一起使用時,void
可以用來強制將 function 關鍵字視為表達式而不是宣告
let 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
運算子的使用。
此規則的錯誤程式碼範例
在 Playground 中開啟
/*eslint no-void: "error"*/
;
const foo = ;
function baz() {
return ;
}
選項
此規則有一個物件選項
allowAsStatement
設定為true
允許將void
運算子用作陳述句(預設為false
)。
allowAsStatement
當 allowAsStatement
設定為 true 時,此規則將不會對 void
運算子用作陳述句的情況報錯,即當它未在表達式位置使用時,例如在變數賦值或函式回傳中。
{ "allowAsStatement": true }
的錯誤程式碼範例
在 Playground 中開啟
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
const foo = ;
function baz() {
return ;
}
{ "allowAsStatement": true }
的正確程式碼範例
在 Playground 中開啟
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
void foo;
void someFunction();
何時不該使用
如果您有意使用 void
運算子,則可以停用此規則。
相關規則
版本
此規則在 ESLint v0.8.0 中引入。
延伸閱讀
