在JS中利益函数求数组【5,2,99,101,67,77】中的最大值
时间: 2024-05-15 14:17:27 浏览: 12
可以使用Math.max()方法和展开语法来求解:
```js
const arr = [5, 2, 99, 101, 67, 77];
const max = Math.max(...arr);
console.log(max); // 输出101
```
通过展开语法,将数组转化为参数序列,传递给Math.max()方法,就可以求出数组中的最大值了。
相关问题
js用函数求数组中最大值和最小值
可以使用 Math 对象中的 max 和 min 方法来求解一个数组中的最大值和最小值,具体实现如下:
```javascript
function findMaxAndMin(arr) {
let max = Math.max.apply(null, arr);
let min = Math.min.apply(null, arr);
return {
max: max,
min: min
};
}
let arr = [1, 2, 3, 4, 5];
let result = findMaxAndMin(arr);
console.log(result.max); // 输出 5
console.log(result.min); // 输出 1
```
在上述代码中,我们定义了一个 `findMaxAndMin` 函数,该函数接收一个数组参数,并使用 `Math.max` 和 `Math.min` 方法来分别求解数组中的最大值和最小值,再将结果封装在一个对象中返回。
js利用函数求数组中的最大值和最小值
可以使用 Math 中的 max 和 min 函数来求一个数组中的最大值和最小值。具体实现如下:
```javascript
function findMaxAndMin(arr) {
let max = Math.max.apply(Math, arr);
let min = Math.min.apply(Math, arr);
return {max, min};
}
let arr = [1, 2, 3, 4, 5, 6];
let result = findMaxAndMin(arr);
console.log(result.max); // 6
console.log(result.min); // 1
```
上面的代码中,我们定义了一个函数 `findMaxAndMin` 来求一个数组的最大值和最小值。在函数内部,我们使用了 `Math.max` 和 `Math.min` 函数来分别求出数组中的最大值和最小值。由于这两个函数的参数需要是一个一个的数字,而不是一个数组,因此我们使用了 `apply` 方法来将数组中的元素依次传递给这两个函数。最后,我们将求出的最大值和最小值放在一个对象中返回。