admin管理员组

文章数量:1208155

This seems to work, on an array of strings that look like numbers (they're numbers from a CSV file read in with csv-parse, which seems to convert everything into strings):

 var a = ['123.1', '1234.0', '97.43', '5678'];
 Math.max.apply(Math, a);

Returns 5678.

Does Math.max convert strings to numbers automatically?

Or should I do a + conversion myself first to be extra safe?

This seems to work, on an array of strings that look like numbers (they're numbers from a CSV file read in with csv-parse, which seems to convert everything into strings):

 var a = ['123.1', '1234.0', '97.43', '5678'];
 Math.max.apply(Math, a);

Returns 5678.

Does Math.max convert strings to numbers automatically?

Or should I do a + conversion myself first to be extra safe?

Share Improve this question asked May 28, 2015 at 10:22 RichardRichard 65.5k134 gold badges355 silver badges567 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

Does Math.max convert strings to numbers automatically?

Quoting the ECMA Script 5.1 Specification for Math.max,

Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.

So, internally all the values are tried to convert to a number before finding the max value and you don't have to explicitly convert the strings to numbers.

But watch out for the NaN results 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

You'll get a NaN if any of the strings aren't numbers, but otherwise it should work fine. I'd add the + just to be safe.

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 cast elements from array to be extra safe..

if you intend to check for the max element in an array of strings using Math.max() method. you can compare the length of reach element

question: var a = ['123.1', '1234.0', '97.43', '5678'];

const checkLength = Math.max.apply(null, a.map(element => element.length));

or using spread operator for shorter form

const checkLength = Math.max(...a.map(element => element.length));

then filter to get all the elements

a.filter(elem => elem.length === checkLength)

本文标签: Is it safe to use JavaScript39s Mathmax on an array of stringsStack Overflow