【发布时间】:2020-01-29 14:00:26
【问题描述】:
我知道带有多个语句的三元运算符可以在 React/JavaScript 中使用:
condition ? (statement1,statement2,...) : (statement);。
Explored 了解它的工作原理。
以下是导致错误的代码:
localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");
错误:
./src/reducers/reducer.js 第 26:21 行:期望一个赋值或函数调用,而是看到一个表达式 no-unused-expressions
搜索关键字以了解有关每个错误的更多信息。
if/else 的类似代码工作正常:
if (localProducts[productFoundAt].qty > 0) {
localProducts[productFoundAt].qty--;
localCartedProducts[iterator].qty++
} else {
alert("More quantity not available");
}
我在这里做错了什么?谢谢您的帮助。 还有为什么类似的代码在这里工作?
let a = 10;
let b = 10;
a==b ? (a-- , b--):alert("Hello World");
console.log(a);
console.log(b);
【问题讨论】:
-
逗号运算符的那些操作数是表达式,而不是语句。
-
这个错误看起来像是来自 ESLint,而不是 JavaScript。
-
您的 linter 正在抱怨,因为当您在任何地方都不需要表达式作为结果时,您不应该使用条件运算符。只需使用
if语句编写适当的可读代码! -
@Justinas 它是有效的,它只是一个无法阅读的烂摊子。
-
@ZainUlAbideen EsLint 并没有说它无效,它抱怨它的风格不好。这正是 linter 的工作。
标签: javascript reactjs conditional-operator