js obtiene los valores máximo y mínimo y los valores de índice correspondientes en la matriz

1. Utilice es6 (desestructuración de matriz, indexOf (método))

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. Utilice JS nativo para implementar esta función, principalmente a través de bucles. 

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)
}

Supongo que te gusta

Origin blog.csdn.net/hyupeng1006/article/details/125082088
Recomendado
Clasificación