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)
我想取出所有具有apple、banana或 的“乘积”的数组元素pear。
filter()所以我这样使用:
const currentPlans = subscriptions.filter(
(subscription) =>
subscription.product ===
('apple' || 'banana' || 'pear')
);
Run Code Online (Sandbox Code Playgroud)
由于数组只有一个实例,apple因此应该currentPlans包含该实例。
但currentPlans返回一个空数组。
我究竟做错了什么?
以下行不会按您的预期工作。右侧首先计算一个值( apple),然后检查是否相等。它从不检查banana或pear。
subscription.product === ("apple" || "banana" || "pear")
Run Code Online (Sandbox Code Playgroud)
您应该使用另一个数组来保持匹配。尝试如下所示。
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)
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |