使用 JavaScript 以最大最小形式重新排列数组
javascriptweb developmentobject oriented programming更新于 2025/10/12 16:44:17
我们需要编写一个函数,例如 minMax(),它接受一个数字数组并重新排列元素,使最大元素首先出现,然后是最小元素,然后是第二大元素,然后是第二小元素,依此类推。
例如 −
// 如果输入数组为: const input = [1, 2, 3, 4, 5, 6, 7] // 那么输出应该是: const output = [7, 1, 6, 2, 5, 3, 4]
那么,让我们为这个函数编写完整的代码 −
示例
const input = [1, 2, 3, 4, 5, 6, 7];
const minMax = arr => {
const array = arr.slice();
array.sort((a, b) => a-b);
for(let start = 0; start < array.length; start += 2){
array.splice(start, 0, array.pop());
}
return array;
};
console.log(minMax(input));
输出
控制台中的输出将是 −
[ 7, 1, 6, 2, 5, 3, 4 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

