Eslint
规则 | Rules

no-unused-expressions

Disallow Unused Expressions (no-unused-expressions)

对程序状态没有影响的未使用表达式表示逻辑错误。

例如,n + 1;不是一个语法错误,但它可能是一个程序员n += 1;代替赋值语句的打字错误。

规则细节

该规则旨在消除对程序状态没有影响的未使用的表达式。

此规则不适用于与new操作员进行函数调用或构造函数调用,因为它们可能会对程序的状态产生副作用

var i = 0; function increment() { i += 1; } increment( // return value is unused, but i changed as a side effect var nThings = 0; function Thing() { nThings += 1; } new Thing( // constructed object is unused, but nThings changed as a side effect

此规则不适用于指令(以字符串表达式的形式,如"use strict";脚本,模块或函数的开头)。

a = 1, b = 2除非在条件评估中分配或使用它们的返回值,或者使用序列表达式值进行函数调用,否则序列表达式(使用逗号等的表达式)始终被视为未使用。

选项

此规则在其默认状态下不需要任何参数。如果您希望启用以下一项或多项操作,则可以按如下方式传递一个设置了选项的对象:

  • allowShortCircuit设置为true允许您在表达式中使用短路评估(默认:)false

  • allowTernary设置为true将允许您在表达式中使用三元运算符,类似于短路评估(默认:)false

  • allowTaggedTemplates设置为true将使您能够在表达式中使用标记的模板文字(默认:)false

只有当所有代码路径直接改变状态(例如赋值语句)或可能有副作用(例如函数调用)时,这些选项才允许未使用的表达式。

不正确的代码为默认{ "allowShortCircuit": false, "allowTernary": false }选项的示例:

/*eslint no-unused-expressions: "error"*/ 0 if(0) 0 {0} f(0), {} a && b() a, b() c = a, b; a() && function namedFunctionInExpressionContext () {f(} (function anIncompleteIIFE () {} injectGlobal`body{ color: red; }`

请注意,如果一个或多个字符串表达式语句(带或不带分号)仅在脚本,模块或函数(单独且不受其他语句中断)开头的情况下才会被视为未使用。否则,它们将被视为“指令序言”的一部分,这是 JavaScript 引擎可能使用的一个部分。这包括“严格模式”指令。

"use strict"; "use asm" "use stricter"; "use babel" "any other strings like this in the prologue";

默认选项的正确代码示例{ "allowShortCircuit": false, "allowTernary": false }

/*eslint no-unused-expressions: "error"*/ {} // In this context, this is a block statement, not an object literal {myLabel: someVar} // In this context, this is a block statement with a label and expression, not an object literal function namedFunctionDeclaration () {} (function aGenuineIIFE () {}() f() a = 0 new C delete a.b void a

allowShortCircuit

选项的错误代码示例{ "allowShortCircuit": true }

/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/ a || b

选项的正确代码示例{ "allowShortCircuit": true }

/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true }]*/ a && b() a() || (b = c)

allowTernary

选项的错误代码示例{ "allowTernary": true }

/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/ a ? b : 0 a ? b : c()

选项的正确代码示例{ "allowTernary": true }

/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/ a ? b() : c() a ? (b = c) : d()

allowShortCircuit and allowTernary

选项的正确代码示例{ "allowShortCircuit": true, "allowTernary": true }

/*eslint no-unused-expressions: ["error", { "allowShortCircuit": true, "allowTernary": true }]*/ a ? b() || (c = d) : e()

allowTaggedTemplates

选项的错误代码示例{ "allowTaggedTemplates": true }

/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/ `some untagged template string`;

选项的正确代码示例{ "allowTaggedTemplates": true }

/*eslint no-unused-expressions: ["error", { "allowTaggedTemplates": true }]*/ tag`some tagged template string`;

版本

该规则在 ESLint 0.1.0中引入。

资源