为什么 X === (A || B || C) 不匹配任何内容?

Tin*_*ger 2 javascript typescript

我有一个看起来像这样的数组:

const subscriptions = [
    {
        "price": "20",
        "product": "apple",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
    {
        "price": "10",
        "product": "orange",
        "quantity": 1,
    },
]
Run Code Online (Sandbox Code Playgroud)

我想取出所有具有applebanana或 的“乘积”的数组元素pear

filter()所以我这样使用:

const currentPlans = subscriptions.filter(
  (subscription) =>
    subscription.product ===
    ('apple' || 'banana' || 'pear')
);
Run Code Online (Sandbox Code Playgroud)

由于数组只有一个实例,apple因此应该currentPlans包含该实例。

currentPlans返回一个空数组。

我究竟做错了什么?

Ami*_*era 5

以下行不会按您的预期工作。右侧首先计算一个值( apple),然后检查是否相等。它从不检查bananapear

subscription.product === ("apple" || "banana" || "pear")
Run Code Online (Sandbox Code Playgroud)

您应该使用另一个数组来保持匹配。尝试如下所示。

使用indexOf

subscription.product === ("apple" || "banana" || "pear")
Run Code Online (Sandbox Code Playgroud)

使用包含

const subscriptions = [ { price: "20", product: "apple", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, { price: "10", product: "orange", quantity: 1, }, ];

const matches = ["apple", "banana", "pear"];

const currentPlans = subscriptions.filter(
  (subscription) => matches.indexOf(subscription.product) >= 0
);

console.log(currentPlans);
Run Code Online (Sandbox Code Playgroud)