js用遍历求最大值最小值
时间: 2023-05-31 07:05:16 浏览: 60
以下是使用遍历求最大值最小值的JavaScript代码:
```javascript
var arr = [12, 56, 78, 23, 45, 89, 34];
// 求最大值
var max = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log("最大值为:" + max);
// 求最小值
var min = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
console.log("最小值为:" + min);
```
解析:
首先定义一个数组`arr`,然后分别使用两个`for`循环遍历数组,分别求出最大值和最小值。在遍历过程中,使用一个变量`max`(或`min`)记录当前已遍历的元素中的最大值(或最小值),如果有比当前最大值(或最小值)更大(或更小)的元素,则更新`max`(或`min`)的值,最终输出结果。
相关问题
js 数组找出最大值和最小值的下标
可以使用循环遍历整个数组,记录最大值和最小值以及它们对应的下标,代码如下:
```javascript
function findMaxAndMinIndex(arr) {
let maxIndex = 0;
let minIndex = 0;
for(let i = 1; i < arr.length; i++) {
if(arr[i] > arr[maxIndex]) {
maxIndex = i;
}
if(arr[i] < arr[minIndex]) {
minIndex = i;
}
}
return {
maxIndex: maxIndex,
minIndex: minIndex
};
}
// 示例
const arr = [1, 5, 3, 9, 2, 8];
const result = findMaxAndMinIndex(arr);
console.log(result.maxIndex); // 输出: 3
console.log(result.minIndex); // 输出: 0
```
上述代码中,我们使用 `maxIndex` 和 `minIndex` 分别记录最大值和最小值在数组中的下标。在循环中,如果找到更大的数,则更新 `maxIndex`,如果找到更小的数,则更新 `minIndex`。最后,返回一个包含 `maxIndex` 和 `minIndex` 的对象。
求数组的最大值和最小值,并输出他们的下标索引js
好的,以下是实现您要求的JavaScript代码:
```javascript
// 创建一个数组
let arr = [10, 5, 23, 8, 17, 20, 3];
// 初始化最大值和最小值为数组的第一个元素
let max = arr[0];
let min = arr[0];
// 初始化最大值和最小值的下标索引为0
let maxIndex = 0;
let minIndex = 0;
// 循环遍历数组中的每个元素
for (let i = 1; i < arr.length; i++) {
// 如果当前元素比最大值大,则更新最大值和最大值的下标索引
if (arr[i] > max) {
max = arr[i];
maxIndex = i;
}
// 如果当前元素比最小值小,则更新最小值和最小值的下标索引
if (arr[i] < min) {
min = arr[i];
minIndex = i;
}
}
// 输出最大值和最小值及其下标索引
console.log(`数组中的最大值为 ${max},下标索引为 ${maxIndex}。`);
console.log(`数组中的最小值为 ${min},下标索引为 ${minIndex}。`);
```
这段代码将创建一个数组 `arr`,然后使用 `for` 循环遍历数组中的每个元素。循环体内使用条件语句判断当前元素是否比最大值或最小值大或小,并在必要时更新最大值和最大值的下标索引,以及最小值和最小值的下标索引。最后,代码将输出最大值和最小值及其下标索引到控制台。
相关推荐
![](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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)