Reputation: 35
I have this simple issue that I can't figure out trying to find out the max from a string, yes it is a string, converting to a float. According to JS it can take an array... but everytime I try to find the max it is just printing the first value. In this case 13... not sure why? The expected result is 30.
Please help. Thanks!
function myFunction() {
var str = "13, 24, 30, 4";//30
var res = str.split(",");
var max = Math.max(parseFloat(res));
document.getElementById("demo").innerHTML = res+ " " + max;//test
}
Upvotes: 0
Views: 581
Reputation: 665555
res
is an array. parseFloat
takes a string. Math.max
does not take an array, but multiple arguments. Notice that you don't even need parseFloat
, as Math.max
casts its arguments to numbers anyway. So you have to use apply
to get the array into Math.max
:
var str = "13, 24, 30, 4";
var max = Math.max.apply(Math, str.split(", "));
document.getElementById("demo").innerHTML = "max("+res+") = "+max;
Upvotes: 5