Can JavaScript Math.max be used on a string array?
This seems to work on an array of strings that look like numbers (these are numbers from a CSV file read with csv-parse
that seems to convert everything to strings):
var a = ['123.1', '1234.0', '97.43', '5678'];
Math.max.apply(Math, a);
Returns 5678
.
Does it convert Math.max
strings to numbers automatically?
Or do I need to do the conversion first +
to be safe?
source to share
Does Math.max convert strings to numbers automatically?
ECMA Script 5.1 Specification for Math.max
,
If there are zero or more arguments, calls
ToNumber
for each of the arguments and returns the largest value obtained.
So internally, all values ββare trying to convert to a number before finding the maximum value, and you don't need to explicitly convert strings to numbers.
But watch out for results NaN
if the string is not a valid number. For example, if the array had one invalid string like this
var a = ['123.1', '1234.0', '97.43', '5678', 'thefourtheye'];
console.log(Math.max.apply(Math, a));
// NaN
source to share