将Math.min()应用于空列表将产生-Infinity而不是0

5 javascript forms

我已经开发了一个代码,其中添加值,最后根据您在表单中选择的项目减去最小值。该代码工作正常,但是当您取消选择所有项目并且显示-Infinity而不是显示0时,会出现问题。我要对此脚本执行什么操作以强制其显示0而不是-Infinity?

// All selected prices are stored on a array
var prices = [];

// A function to remove a item from an array
function remove(array, item) {
    for (var i = 0, len = array.length; i < len; i++) {
        if (array[i] == item) {
            array.splice(i, 1);
            return true;
        }
    }
    return false;
}

function calculateSectedDues(checkbox, amount) {
    // We add or remove the price as necesary

    if (checkbox.checked) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    // We sum all the prices
    var total = 0;
    for (var i = 0, len = prices.length; i < len; i++)
        total += prices[i];

    // We get the lower one
    var min = Math.min.apply(Math, prices);

    // And substract it
    total -= min;

    // Please, don't access the DOM elements this way, use document.getElementById instead
    document.grad_enroll_form.total.value = total;

}


</script>
Run Code Online (Sandbox Code Playgroud)

aps*_*ers 6

Math.min()不带参数返回Infinity,这就是Math.min.apply(Math, prices)使用空prices数组调用时发生的情况。

为什么不检测Infinity最小值的存在并将其重置为零?

// We get the lower one
var min = Math.min.apply(Math, prices);

// ** test for Infinity **
if(min == Infinity) { min = 0; }

// And substract it
total -= min;
Run Code Online (Sandbox Code Playgroud)

或者确保prices至少有一个元素:

// fill the empty array with a zero
if(prices.length == 0) prices.push(0);

// We get the lower one
var min = Math.min.apply(Math, prices);
Run Code Online (Sandbox Code Playgroud)