2 回答

TA贡献1795条经验 获得超7个赞
仅按升序中途显示原始数组的问题,而按降序中途显示原始数组的问题是,输出将为80、70、60、50、10、20、30、40,因为当数组获取消息时开始降序排序会将所有从50开始的数字放在10 20 30 40之前,因为它的数字更高,需要先行。
因此,要获得10、20、30、40、80、70、60、50的输出,可以将数组拆分为2个新数组,然后对其进行排序,然后再次将它们组合在一起,如下所示:
function sortArrays(a) {
//slices the value of the passed in array in half, and makes 2 new arrays of it
var arrayLength1 = a.length;
var arrayHalf = arrayLength1 / 2;
var firstHalf = a.slice(0,arrayHalf);
var secondHalf = a.slice(arrayHalf);
// sorts one array ascending and the other descending
firstHalf.sort(ascendingFunction);
secondHalf.sort(descendingFunction);
//combines together the 2 arrays, already sorted one ascending and one descending
var newSortedArray = firstHalf.concat(secondHalf);
alert(newSortedArray); // the output you want
}
function ascendingFunction(a,b){
return a - b
}
function descendingFunction(a,b){
return b - a
}
var one = [10, 20, 30, 40, 50, 60, 70, 80];
var two = [60, 70, 80, 90, 100, 110, 120, 130];
现在您可以调用该函数并传入所需的任何数组,例如:
sortArrays(one);
sortArrays(two);

TA贡献1836条经验 获得超5个赞
您有很多语法错误-您还试图对Array自身进行排序,这是您不应该做的。您需要按升序和降序对放入的数组进行排序,然后将其写出:
function compareArrays(arr1, arr2) {
arr1.sort((a, b) => b - a);
arr2.sort((a, b) => b - a);
console.log(`First in ascending order: ${arr1[0]} and ${arr2[0]}`);
arr1.sort((a, b) => a - b);
arr2.sort((a, b) => a - b);
console.log(`Last in descending order: ${arr1[arr1.length - 1]} and ${arr2[arr2.length - 1]}`);
}
var one = [10, 20, 30, 40, 50, 60, 70, 80];
var two = [60, 70, 80, 90, 100, 110, 120, 130, 140, 150];
compareArrays(one, two);
.as-console-wrapper { max-height: 100% !important; top: auto; }
添加回答
举报