2013-04-16 2 views
4

Я разработал код, в котором добавляются значения и в конце вычитает наименьшее значение на основе элементов, которые вы выбираете в форме. Код работает отлично, однако проблема возникает, когда вы снимаете с себя все элементы и вместо отображения 0 отображает -Infinity. Что мне делать с этим скриптом, чтобы заставить его отображать 0 вместо -Infinity?Применение Math.min() в пустом списке создает -Infinity вместо 0

// 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> 

ответ

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); 
+0

Спасибо за вашу помощь @apsillers! – 2013-04-16 20:49:37

+0

@Alfie_Fitz Исходные нули отбрасываются в JavaScript. Вы можете использовать '.toFixed (2)', чтобы показать номер как строку с двумя десятичными знаками. (Взгляните на [Является ли JavaScript с плавающей запятой Math Broken?] (Http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken), чтобы понять общие проблемы с числами с плавающей запятой.) – apsillers

Смежные вопросы