Я разработал код, в котором добавляются значения и в конце вычитает наименьшее значение на основе элементов, которые вы выбираете в форме. Код работает отлично, однако проблема возникает, когда вы снимаете с себя все элементы и вместо отображения 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>
Спасибо за вашу помощь @apsillers! – 2013-04-16 20:49:37
@Alfie_Fitz Исходные нули отбрасываются в JavaScript. Вы можете использовать '.toFixed (2)', чтобы показать номер как строку с двумя десятичными знаками. (Взгляните на [Является ли JavaScript с плавающей запятой Math Broken?] (Http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken), чтобы понять общие проблемы с числами с плавающей запятой.) – apsillers