Javascript find closest number in array without going under

前端 未结 3 1231
花落未央
花落未央 2021-01-12 02:59

I have an array of numbers, for example [300, 500, 700, 1000, 2000, 3000] and I want to find the closest number, without going under the number given.

F

3条回答
  •  自闭症患者
    2021-01-12 03:21

    var list = [300, 500, 700, 1000, 2000, 3000];
    
    function findBestMatch(toMatch) {
        // Assumes the array is sorted.
    
        var bestMatch = null;
        var max = Number.MIN_VALUE;
        var item;
    
        for (var i = 0; i < list.length; i++) {
            item = list[i];
    
            if (item > toMatch) {
                bestMatch = item;
                break;
            }
    
            max = Math.max(max, item);
    
        }
    
        //  Compare to null, just in case bestMatch is 0 itself.
        if (bestMatch !== null) {
            return bestMatch;
        }
    
        return max;
    
    }
    
    alert(findBestMatch(2200));
    alert(findBestMatch(3200));
    

提交回复
热议问题