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?
4 Answers
Reset to default 14Does 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
版权声明:本文标题:Is it safe to use JavaScript's Math.max on an array of strings? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738732714a2109415.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论