Eslint
规则 | Rules

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 0短于undefined

foo = void 0; foo = undefined;

与 IIFE(立即调用函数表达式)一起使用时,void可用于强制将函数关键字视为表达式而不是声明:

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操作员,将其标记为不明显且难以阅读。

规则细节

此规则旨在消除无效操作符的使用。

此规则的错误代码示例:

/*eslint no-void: "error"*/ void foo var foo = void bar(

何时不使用它

如果您故意使用void操作员,则可以禁用此规则。

进一步阅读

相关规则

  • no-undef-init

  • no-undefined

版本

这条规则是在 ESLint 0.8.0中引入的。

资源