为什么 Math.max() 需要扩展运算符?

问题描述 投票:0回答:3
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))
结果为
NaN
console.log(Math.Max(...lengths))
有效。为什么需要扩展长度? Math.Max 采用数组作为参数,&lengths 是数组吗?谢谢

javascript arrays
3个回答
6
投票

Math.max
不采用数组。它需要一组参数。扩展运算符提供数组的所有值作为单独的参数。

Math.max(...lengths)

实际上在运行时表示为:

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

2
投票

Math.Max 将数组作为参数

事实并非如此根据MDN

Math.max() 函数返回作为输入参数给出的零个或多个数字中的最大值,如果任何参数不是数字且无法转换为 1,则返回 NaN。


0
投票

如果您因为收到此错误而来到这里。 JavaScript console that shows the error

我的原始代码是扩展一个数组来查找最大值。
我的数组太大了,这导致了错误。

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

可以通过使用reduce 来缓解这种情况。

let myArray = [1, 2, 2, 4, 3];
let max = finalMask.reduce((max, cur) => Math.max(max, cur), 0);
// `max` returns 4
© www.soinside.com 2019 - 2024. All rights reserved.