网站首页 网站地图
网站首页 > 娱乐人生 > 两头小中间大怎么编程

两头小中间大怎么编程

时间:2026-03-20 18:23:46

要实现中间大两边小的数组,你可以按照以下步骤进行:

排序数组 :首先将数组从大到小排序。

遍历数组:

然后遍历排序后的数组,根据索引的奇偶性将元素添加到新的数组中。奇数索引的元素添加到新数组的尾部,偶数索引的元素添加到新数组的头部。

```javascript

let arrCount = [1, 4, 5, 8, 89, 44, 15, 13, 110, 120, 150];

let newCount = [];

// 将数组从大到小排序

arrCount.sort(function (a, b) {

return b - a;

});

// 遍历数组,根据索引的奇偶性将元素添加到新数组中

arrCount.forEach((item, index) => {

if (index % 2) {

// 偶数索引,添加到尾部

newCount.push(item);

} else {

// 奇数索引,添加到头部

newCount.unshift(item);

}

});

console.log(newCount); // 输出: [110, 150, 120, 89, 44, 15, 13, 5, 8, 4, 1]

```

解释

排序数组:

`arrCount.sort(function (a, b) { return b - a; });` 这一行代码将数组从大到小排序。

遍历数组:

`arrCount.forEach((item, index) => { ... });` 这一行代码遍历排序后的数组。

根据索引添加元素

`if (index % 2)`:判断索引是否为偶数。

`newCount.push(item)`:如果索引为偶数,将元素添加到新数组的尾部。

`newCount.unshift(item)`:如果索引为奇数,将元素添加到新数组的头部。

通过这种方式,你可以得到一个中间元素最大,两边元素逐渐减小的数组。