Using Math.min () on an empty list causes -Infinity instead of 0

I developed a code in which values ​​are added and in the end it subtracts the smallest value based on the elements you select in the form. The code works fine, but the problem arises when you take off all the elements and display -Infinity instead of 0. What should I do with this script to make it display 0 instead of -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> 
+4
source share
1 answer

Math.min() with no arguments returns Infinity , which happens when you call Math.min.apply(Math, prices) with an empty prices array.

Why not just detect the presence of a minimum of Infinity and reset to zero?

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

Or make sure prices has at least one element:

 // 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); 
+3
source

All Articles