鍍金池/ 問答/HTML/ JS 如何對數(shù)量不確定的目標(biāo)進(jìn)行數(shù)值大小對比?

JS 如何對數(shù)量不確定的目標(biāo)進(jìn)行數(shù)值大小對比?

RT:JS 如何對數(shù)量不確定的目標(biāo)進(jìn)行數(shù)值大小對比?

const rects = [
    {width: 12, height: 34},
    {width: 9, height: 32},
    {width: 32, height: 64},
    {width: 13, height: 84},
    {width: 2, height: 94},
]

rects.forEach(item => {
    item.height //怎么得出最大得值?
})

我能想到的是逐步一個個對比,保存單前最大值再和下一個值對比,有沒有簡單的辦法實(shí)現(xiàn)?

回答
編輯回答
薄荷綠

調(diào)用數(shù)組中的sort方法進(jìn)行排序,如果你要的是降序排序的話,就直接去第一個就行了

2017年8月22日 19:53
編輯回答
陌離殤
Math.max(...rects.map(o=>o.height)) //獲取最大值

rects.find(v=>v.height===Math.max(...rects.map(o=>o.height))) //獲取最大值對象

rects.findIndex(v=>v.height===Math.max(...rects.map(o=>o.height)))//獲取最大值對象的index
2018年2月12日 08:07