发布于 3年前

js 2种方法从数组里面找到最接近某个数值的值(小于该指定值,并且大于其他值)

1、用于递归查找

var arr = [6,8,1,6,8,7,9,10,11,55,74,12,3,5,6,8,9,4,2,3,5,4,86,31,5]
let testStr = 0
let testArr = []
function MaxFn (str, arr) {
    let list = []
    arr.forEach((el, index) => {
        if (el < str && el > testStr) {
            list.push(el)
        } else if (el < testStr || el > testStr) {
            list.splice(index, 1)
        }
        testStr = el
    })
    testArr = list
    if (list.length != 1) {
        MaxFn(str, list)
    }
}
MaxFn (74, arr)
console.log(testArr)
// 比如我想找74最接近他的值(注意:找到的值必须是小于这个值的,大于则排除)
// 那我找到的值就是55。

// 我想找接近10的,那我找到的就是9

2、 通过找到所有小于该指定值的所有数值,并且把他们放到数组里面,以小到大排序,让后取数组最后一位

var arr = [6,8,1,6,8,7,9,10,11,55,74,12,3,5,6,8,9,4,2,3,5,4,86,31,5]
function MaxFn (str, arr) {
    let list = []
    arr.forEach((el, index) => {
    // 1、在所有时间里面找出小于当前时间
        if (el < str) {
        // 2、把所有小于当前时间的时间整合到数组
            list.push(el)
        }
    })
    // 3、数组从小到大排序
    list.sort(function(a,b){return a-b;});
    // 4、从排序的数组里面获取最后一位
    return list[list.length-1]
}
console.log(MaxFn(10, arr))
©2020 edoou.com   京ICP备16001874号-3