用JS利用函数求数组[1,34,5,24,54]里最大值,带有return
时间: 2024-06-06 09:11:17 浏览: 11
function getMax(arr){
let max = arr[0];
for(let i=1; i<arr.length; i++){
if(arr[i]>max){
max = arr[i];
}
}
return max;
}
console.log(getMax([1,34,5,24,54])); // Output: 54
相关问题
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` 方法来将数组中的元素依次传递给这两个函数。最后,我们将求出的最大值和最小值放在一个对象中返回。
利用函数求出数组里面的最大值
好的,可以使用以下的 Python 代码来实现求出数组里面的最大值:
```python
def find_max(arr):
max_val = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
return max_val
```
其中,`arr` 是输入的数组,`max_val` 是当前找到的最大值。
这个函数会遍历整个数组,对于每个元素,如果它比 `max_val` 大,就更新 `max_val`。最后返回 `max_val` 即为数组里面的最大值。
你可以在调用这个函数时传入任意一个数组作为参数,例如:`find_max([1, 3, 5, 2, 4])`,它会返回 `5`,也就是这个数组里面的最大值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)