JS中两个数组取最大值

发布时间 2023-12-15 15:25:37作者: Kllin

如果你有两个数组,并且想要找到它们中的最大值,你可以使用 Math.max() 方法结合展开运算符 ... 来实现。以下是示例代码:

const array1 = [5, 8, 2, 10];
const array2 = [3, 6, 4, 9];

// 使用展开运算符将两个数组合并为一个新数组
const combinedArray = [...array1, ...array2];

// 使用 Math.max() 方法找到最大值
const max = Math.max(...combinedArray);

console.log(max);

在上述代码中,我们首先使用展开运算符 ... 将两个数组 array1array2 合并为一个新数组 combinedArray。然后,使用 Math.max() 方法和展开运算符 ... 找到 combinedArray 中的最大值,并将结果赋值给变量 max。最后,使用 console.log() 打印最大值。