我知 Prop 有多个语句的三元运算符可以在 React/JavaScript 中使用:
条件? (语句1,语句2,...):(语句);
。
Explored了解它是如何工作的。
以下是我的代码,它导致了错误:
localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");
错误:
./src/reducers/reducer.js Line 26:21: Expected an assignment or function call and instead saw an expression no-unused-expressions
Search for the keywords to learn more about each error.
与 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);
最佳答案
这是一个有效的语法。这只是一个 es-lint
错误,您可以通过添加以下行来忽略该错误:
/* eslint-disable no-unused-expressions */
localProducts[productFoundAt].qty > 0 ? (localProducts[productFoundAt].qty-- , localCartedProducts[iterator].qty++) : alert("More quantity not available");
希望这对您有用。
关于javascript - 为什么 JS 中带有多个语句的三元运算符不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59968688/