需求:找到商品數組中價格最小的商品
商品結構如下:
const cars= [
{
sku: '11-02e',
attributes: {
price: 119
},
name: '黑色'
}, {
sku: '11-02f',
attributes: {
price: 121
},
name: '白色'
}, {
sku: '11-02g',
attributes: {
price: 35
},
name: '紅色'
}
]
查找方法如下:
getLowestPrice() {
const lowPrice = Math.min.apply(Math, this.cars.map(item => item.attributes.price))
return {
product: JSON.parse(JSON.stringify(this.cars.find(item => lowPrice === item.attributes.price))),
index: this.cars.findIndex(item => lowPrice === item.attributes.price)
}
}
this.getLowestPrice()
打印結構如下:
解釋如下:
Math.min() 返回零個或更多個數值的最小值。
Math.min.apply(Math, this.cars.map(item => item.attributes.price)) // 獲取數組裏price的最小值
find() 方法返回通過測試(函數內判斷)的數組的第一個元素的值。
this.cars.find(item => lowPrice === item.attributes.price) // 返回滿足條件的item
findIndex()方法返回數組中滿足提供的測試函數的第一個元素的索引。否則返回-1。
this.cars.findIndex(item => lowPrice === item.attributes.price)