我需要编写一个接受两个输入的函数,即“目标”(整数)和“值”(整数列表),并找出“值”中的哪个数字最接近“目标”。我想出了以下几点:

var targetNum = 0;
var valuesArr = [2, 4, 6, 8, 10];

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
    }
    return currVal;
}
alert(closestToTarget(targetNum, valuesArr));


该函数有效,但是如果出现平局,我将无法返回较小的值。我能想到的最好的是以下无效的方法:

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
        else if (currDiff == diff) {
            return Math.min[currVal, values[i]];
        }
        else {
            return currVal[i - 1];
        }
    }
    return currVal;
}


如果是平局,如何在JavaScript中返回较小的数字?

最佳答案

您的想法应该可行,但您也可以使用第一个函数,但要添加一些可以在最后检查是否平局的东西:

function closestToTarget(target, values) {
    var currVal = values[0];
    var diff = Math.abs(target - currVal);
    for (var i = 0; i < values.length; i++) {
        var currDiff = Math.abs(target - values[i]);
        if (currDiff < diff) {
            diff = currDiff;
            currVal = values[i];
        }
    }

    // We found the closest but now check if there's a smaller tie
    if (currVal > target && values.indexOf(target - diff) > -1 ) {
        return target - diff;
    }
    else {
    // if not just return what we originally found
        return currVal;
    }
}


https://jsfiddle.net/vsj0q5u9/2/

07-24 09:23