在 JavaScript 中不使用 sort() 对数组进行排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/8 23:40:17
我们需要编写一个接受数字数组的 JavaScript 函数。
该函数应该使用 Array.prototype.sort() 方法对数组进行排序,但是,在这里,我们需要使用 Array.prototype.reduce() 方法对数组进行排序。
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr = [4, 56, 5, 3, 34, 37, 89, 57, 98];
const sortWithReduce = arr => {
return arr.reduce((acc, val) => {
let ind = 0;
while(ind < arr.length && val < arr[ind]){
ind++;
}
acc.splice(ind, 0, val);
return acc;
}, []);
};
console.log(sortWithReduce(arr));
输出
控制台中的输出将是 −
[ 98, 57, 89, 37, 34, 5, 56, 4, 3 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

