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

时间:2013-04-16 20:32:50

标签: javascript forms

我开发了一个代码,在其中添加值,最后根据您在表单中选择的项目减去最小值。代码工作正常但是当您取消选择所有项目而不是显示0时会出现问题,它会显示-Infinity。如何对此脚本强制显示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>

1 个答案:

答案 0 :(得分:3)

没有参数的

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;

或确保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);