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 是数组吗?谢谢
Math.max
不采用数组。它需要一组参数。扩展运算符提供数组的所有值作为单独的参数。
Math.max(...lengths)
实际上在运行时表示为:
Math.max(lengths[0], lengths[1], etc, lengths[n])
如果您因为收到此错误而来到这里。
我的原始代码是扩展一个数组来查找最大值。
我的数组太大了,这导致了错误。
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