js利用函数求数组中的最大值和最小值
时间: 2023-08-08 10:08:55 浏览: 68
可以使用 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` 方法来将数组中的元素依次传递给这两个函数。最后,我们将求出的最大值和最小值放在一个对象中返回。
相关问题
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中定义一个函数求数组的最大值和最小值并将最大值和最小的值返回
可以回答这个问题。以下是一个示例代码:
```
function findMinMax(arr) {
let min = arr[0];
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
return [min, max];
}
let arr = [1, 2, 3, 4, 5];
let [min, max] = findMinMax(arr);
console.log(`最小值为 ${min},最大值为 ${max}`);
```
输出结果为:
```
最小值为 1,最大值为 5
```