這是一個購物車。如何遍歷對象文字數組以找到匹配的屬性?
我想檢索regularListings中的物品的價格,並使用它們來計算我的購物車的總數。
購物車'michael'中的第一項是顧客的名字。
這怎麼能在JavaScript中完成?
'use strict'
const listing =
(name, price) => ({
name,
price
})
const cart =
(customer, ...items) => ({
customer,
items
})
const listedPrice =
listing =>
name =>
name === listing.name
? listing.price
: 0
const regularListings = [
listing('detergent', 10),
listing('hennessey', 100),
listing('carlo rozzi', 20),
listing('coffee', 5),
listing('cookies', 6),
listing('mountain dew', 2)
]
const carts = [
cart(
'michael',
'coffee',
'hennessey',
'coffee',
'hennessey',
'coffee',
'hennessey'
)
]
你會碰到一個問題:對象的屬性有沒有保證的順序。您的購物車應該可能是一個數組,而不是一個對象。 – Pointy