我有一個看起來像這樣的陣列:
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,
},
]
我想用 , 或 的“產品”提取所有apple陣列banana元素pear。
所以我這樣使用filter():
const currentPlans = subscriptions.filter(
(subscription) =>
subscription.product ===
('apple' || 'banana' || 'pear')
);
由于陣列只有一次實體apple,應該是currentPlans包含的內容。
但是currentPlans回傳一個空陣列。
我究竟做錯了什么?
uj5u.com熱心網友回復:
以下行不會像您預期的那樣作業。右側首先評估一個值(apple),然后檢查是否相等。它從不檢查bananaor pear。
subscription.product === ("apple" || "banana" || "pear")
您應該使用另一個陣列來保持匹配。嘗試如下。
使用 indexOf
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);
使用包含
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.includes(subscription.product)
);
console.log(currentPlans);
uj5u.com熱心網友回復:
當您對等式檢查使用條件檢查時,根據優先級,首先計算等式檢查右側的運算式,因此,當您這樣做時'apple'||'banana'||'pear',僅對該陳述句進行求值,然后針對運算式進行檢查在左手邊。
因此'apple'||'banana'||'pear',將評估該值是否真實,apple并且當您subscription.product根據過濾器陣列檢查該值時,將有效地回傳屬性值為 的product物件apple。
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 currentPlans = subscriptions.filter(
(subscription) =>
subscription.product ===
('apple' || 'banana' || 'pear')
);
console.log(currentPlans)
apple盡管當您想要根據條件檢查過濾掉值時,這在過濾其產品值為邏輯在技術上不正確的物件時會起作用。如上所述,條件OR將始終回傳第一個值,即 ,apple并根據每個可迭代值檢查該值。為了實際使用條件檢查,您必須單獨檢查該值與其他所有值,如下所示:
const currentPlans = subscriptions.filter(
(subscription) =>
subscription.product === 'apple' || subscription.product === 'banana' || subscription.product === 'pear'
);
或者,更簡單的方法是通過將所有值壓縮到一個陣列中并呼叫該includes方法并將當前的可迭代值作為引數傳遞。
const currentPlans = subscriptions.filter(
(subscription) =>
['apple' || 'banana' || 'pear'].includes(subscription.product)
);
uj5u.com熱心網友回復:
改成
const currentPlans = subscriptions.filter(
(subscription) =>
(subscription.product ===
'apple' || 'banana' || 'pear')
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/469002.html
標籤:javascript 打字稿
上一篇:React組件的問題
下一篇:使用jQuery替換元素
