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?

+3


source to share


3 answers


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

      

+8


source


You will get NaN

if any string is not a number, but it should work fine otherwise. I would add +

just to be safe.



+1


source


Consider this situation:

<script>
    var a=['123.1', '1234.0', '97.43', '5678','0               11111111'];
    console.log(Math.max.apply(Math, a));
</script>

      

You need to make the elements from the array more secure.

0


source







All Articles