jsは配列内の最大値と最小値、および対応するインデックス値を取得します

1. es6を使用(配列の分割、indexOf(メソッド))

getIndexMAx = (arr) => {
    const maxNum = Math.max(...arr)
    const minNum = Math.min(...arr)
    const [maxIndex, minIndex] = [arr.indexOf(maxNum), arr.indexOf(minNum)]
    console.log(maxNum, minNum, maxIndex, minIndex)
}

2. ネイティブ Js を使用して、主にループを通じてこの機能を実現します 

getMaxMin = (data, key) => {
    if (!data) {
        return false
    }
    let maxIndex = 0
    let minIndex = 0
    let maxNum = data[0][key] || 0
    let minNum = (data[0][key] && data[0][key] !== 0) ? Infinity : data[0][key]
    data.forEach((item, index) => {
        if (item[key] >= maxNum && item[key] !== undefined) {
            maxNum = item[key]
            maxIndex = index
        }
        if (item[key] <= minNum && item[key] !== undefined) {
            minNum = item[key]
            minIndex = index
        }
    })
    console.log(maxNum, minNum, maxIndex, minIndex)
}

おすすめ

転載: blog.csdn.net/hyupeng1006/article/details/125082088