为什么Math.max()需要排列运算符


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))导致NaNconsole.log(Math.Max(...lengths))起作用。为什么需要展开长度?Math.Max以数组为参数,&长度是一个数组?感谢

Math.max不接受数组。它需要一组参数。排列运算符将数组的所有值作为单独的参数提供。

Math.max(...lengths)

在运行时实际表示为:

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

Math.Max将数组作为其参数

根据MDN:,情况并非如此

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

最新更新