JavaScript中的扩展数组符号

4
下面的代码是如何工作的?
array=[1,2,3];

Math.max(array)
NaN

Math.max(...array)
3

为什么不能在一个数组上使用max方法?还有...符号是什么意思?它常见吗?还是像三元运算符一样的缩写?


3
查阅 Math.max 的文档。它不接受数组,因此你不能将数组传递给它(有意义)。 ... 是扩展语法。 - CertainPerformance
请参阅MDN:扩展语法,以及ECMA-262:SpreadElement - RobG
2个回答

6

Math.max() 只接受值,不接受数组,当您使用展开运算符...)时,您提供这些值,这就是它能够工作的原因:

array=[1,2,3];

Math.max(...array) // Math.max(1, 2, 3)

console.log(Math.max(array)) // NaN
console.log(Math.max(...array)) // 3
console.log(Math.max(1, 2, 3)) // 3

如果您需要将函数Math.max()应用于数组,您需要使用Function.prototype.apply()

array=[1,2,3];
    
Math.max.apply(null, array) // Math.max(1, 2, 3)
    
console.log(Math.max(1, 2, 3)) // 3
console.log(Math.max.apply(null, array)) // 3

希望这可以帮助!

0

Math.max 函数只接受一系列的值,而不是一个数组。这个 Math.max(...array) 能够工作是因为 扩展语法 "spread" 了数组并使用其中的值 -> Math.max(1, 2, 3)

如果你真的需要使用数组,因为 扩展语法 不兼容你正在使用的当前 js 引擎,你可以使用函数 Function.prototype.apply

let array = [1, 2, 3];
console.log(Math.max.apply(null, array));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接