最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is the spread operator needed for Math.max()? - Stack Overflow

programmeradmin1浏览0评论
function findLongestWordLength(str) {
let arr = str.split(' '); 
let lengths = arr.map(word => word.length);

console.log(Math.max(lengths));
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

console.log(Math.max(lengths)) results in NaN, console.log(Math.Max(...lengths)) works. Why does lengths need to be spreaded? Math.Max takes an array as its argument, & lengths is an array? Thanks

function findLongestWordLength(str) {
let arr = str.split(' '); 
let lengths = arr.map(word => word.length);

console.log(Math.max(lengths));
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

console.log(Math.max(lengths)) results in NaN, console.log(Math.Max(...lengths)) works. Why does lengths need to be spreaded? Math.Max takes an array as its argument, & lengths is an array? Thanks

Share Improve this question asked Feb 1, 2022 at 16:37 Denby101Denby101 1511 silver badge7 bronze badges 3
  • 2 Wele to StackOverflow. Have you had a chance to review the documentation for Math.max? Please try this and let us know if it helps. – jsN00b Commented Feb 1, 2022 at 16:40
  • 4 Math.max does not take an array as an argument. It takes zero or more numbers as arguments. – Heretic Monkey Commented Feb 1, 2022 at 16:40
  • 2 Math.max does not take an array as argument. It takes one (could be none really) or more values. Math.max(value0, value1, /* ... ,*/ valueN) . See here – R. Schifini Commented Feb 1, 2022 at 16:41
Add a ment  | 

3 Answers 3

Reset to default 8

Math.max does not take an array. It takes a set of parameters. The spread operator provides all of the values of the array as individual parameters.

Math.max(...lengths)

is actually represented at runtime as:

Math.max(lengths[0], lengths[1], etc, lengths[n])

Math.Max takes an array as its argument

This is not the case according to MDN:

The Math.max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.

If you're ing here because you are getting this error.

My original code was spreading an array to find the max.
My array was so large, that this was causing an error.

let myArray = [1, 2, 2, 4, 3];
let max = Math.max(...myArray);
// `max` returns 4

This can be mitigated by using a reduce instead.

let myArray = [1, 2, 2, 4, 3];
let max = myArray.reduce((max, cur) => Math.max(max, cur), Number.NEGATIVE_INFINITY);
// `max` returns 4
发布评论

评论列表(0)

  1. 暂无评论