no-void
禁止 void 运算符
此规则目前已 冻结,不接受功能请求。
void 运算符接受一个操作数并返回 undefined:void expression 将计算 expression 并返回 undefined。它可以用来忽略 expression 可能产生的任何副作用:
🌐 The void operator takes an operand and returns undefined: void expression will evaluate expression and return undefined. It can be used to ignore any side effects expression may produce:
使用 void 操作符的常见情况是获取“纯” undefined 值,因为在 ES5 之前,undefined 变量是可变的:
🌐 The common case of using void operator is to get a “pure” undefined value as prior to ES5 the undefined variable was mutable:
// 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 短:
🌐 Another common case is to minify code as void 0 is shorter than undefined:
foo = void 0;
foo = undefined;
当与 IIFE(立即调用的函数表达式)一起使用时,void 可以用来强制将 function 关键字视为表达式而不是声明:
🌐 When used with IIFE (immediately-invoked function expression), void can be used to force the function keyword to be treated as an expression instead of a declaration:
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 操作符,认为它不直观且难以阅读。
🌐 Some code styles prohibit void operator, marking it as non-obvious and hard to read.
规则详情
🌐 Rule Details
此规则旨在消除 void 运算符的使用。
🌐 This rule aims to eliminate use of void operator.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-void: "error"*/
void foo
void someFunction();
const foo = void bar();
function baz() {
return void 0;
}
选项
🌐 Options
此规则有一个对象选项:
🌐 This rule has an object option:
allowAsStatement设置为true允许将void运算符作为语句使用(默认false)。
allowAsStatement
当 allowAsStatement 设置为 true 时,该规则在 void 操作符被用作语句的情况下不会报错,即当它没有在表达式位置使用时,比如在变量赋值或函数返回中。
🌐 When allowAsStatement is set to true, the rule will not error on cases that the void operator is used as a statement, i.e. when it’s not used in an expression position, like in a variable assignment or a function return.
{ “allowAsStatement”: true } 的错误代码示例:
🌐 Examples of incorrect code for { "allowAsStatement": true }:
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
const foo = void bar();
function baz() {
return void 0;
}
{ “allowAsStatement”: true } 的正确代码示例:
🌐 Examples of correct code for { "allowAsStatement": true }:
/*eslint no-void: ["error", { "allowAsStatement": true }]*/
void foo;
void someFunction();
何时不使用
🌐 When Not To Use It
如果你故意使用 void 操作符,那么你可以禁用此规则。
🌐 If you intentionally use the void operator then you can disable this rule.
相关规则
版本
此规则是在 ESLint v0.8.0 中引入。