为什么带有多个语句的 JS 中的三元运算符不起作用?

Why ternary operator in JS with multiple statements is not working?

我知道具有多个语句的三元运算符在 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 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");

希望这对你有用。