定义一个数组,元素如下:8,4,2,1,23,344,12 1.计算列表中所有元素的和 2.输出列表中最大值和最小值 3.将最大值和第一个元素交换,最小值和最后一个元素交换 (其他元素不动)
时间: 2024-11-17 20:28:24 浏览: 13
当然,我们可以按照您的要求定义一个数组并完成这些操作。首先,我们定义数组:
```javascript
let numbers = [8, 4, 2, 1, 23, 344, 12];
```
接下来,我们逐一解答您的问题:
1. 计算列表中所有元素的和:
```javascript
let sum = numbers.reduce((total, current) => total + current, 0);
console.log("元素之和:", sum);
```
2. 输出列表中的最大值和最小值:
```javascript
let min = Math.min(...numbers);
let max = Math.max(...numbers);
console.log("最小值:", min);
console.log("最大值:", max);
```
3. 将最大值和第一个元素交换,最小值和最后一个元素交换:
```javascript
// 获取索引
let firstIndex = 0;
let lastIndex = numbers.length - 1;
// 检查是否是最小值和最大值
if (min === numbers[firstIndex]) {
// 如果不是,则直接交换
[numbers[0], numbers[lastIndex]] = [numbers[lastIndex], numbers[0]];
} else {
// 找到对应位置进行交换
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === min) {
numbers[i] = numbers[lastIndex];
numbers[lastIndex] = min;
break;
}
}
}
if (max === numbers[firstIndex]) {
// 同样检查非第一个元素
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === max && i !== firstIndex) {
numbers[i] = numbers[0];
numbers[0] = max;
break;
}
}
}
console.log("交换后的数组:", numbers);
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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)