js求数组中所有元素的最大和最小值
时间: 2024-05-11 11:15:39 浏览: 13
可以使用JavaScript中的Math对象中的max和min方法来找到数组中的最大值和最小值:
```
let arr = [5, 2, 8, 1, 9];
let max = Math.max(...arr);
let min = Math.min(...arr);
console.log(`数组中最大的数是${max},最小的数是${min}`);
```
输出结果为:数组中最大的数是9,最小的数是1
相关问题
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` 方法来将数组中的元素依次传递给这两个函数。最后,我们将求出的最大值和最小值放在一个对象中返回。
使用JavaScript编写:利用数组方式变量数组,计算数组中所有元素的和,遍历数组中的元素,获取数组中的最大值和最小值,将求出的和,最大值,最小值显示在页面中
好的,以下是使用JavaScript编写的代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>数组操作</title>
</head>
<body>
<h1>数组操作</h1>
<p>数组元素和:<span id="sum"></span></p>
<p>最大值:<span id="max"></span></p>
<p>最小值:<span id="min"></span></p>
<script>
// 定义数组
var arr = [1, 2, 3, 4, 5];
// 计算数组元素和
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
document.getElementById("sum").innerHTML = sum;
// 获取数组中的最大值和最小值
var max = arr[0];
var min = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
document.getElementById("max").innerHTML = max;
document.getElementById("min").innerHTML = min;
</script>
</body>
</html>
```
代码解释:
1. 首先定义了一个数组 `arr`,其中包含了一些整数。
2. 使用 `for` 循环遍历数组中的每一个元素,计算它们的和,最后将和显示在页面中。
3. 再次使用 `for` 循环遍历数组中的每一个元素,找到其中的最大值和最小值,最后将它们显示在页面中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)