猿问

以降序和升序对数组进行排序

编写一个名为compareArrays()的函数,该函数接受两个数组(每个数组的长度可以是任意数字),并将这两个数组的第一个元素以升序写入页面。它还以降序写入这两个数组的最后一个元素。我可以在我的代码中更正什么?问题出在哪儿?前四个元素应升序,后四个元素应降序。


function compareArrays(y, z) {


  for (x = 0; x < y.length; y++) {

    Array.sort((Function(y, z) {

        return z - y

      });


    }

    for (p = 0; p < z.length; z++) {

      Array.sort((function(y, z) {

          return y - z

        })

      }

    }

    var one = [10, 20, 30, 40, 50, 60, 70, 80];


    var two = [60, 70, 80, 90, 100, 110, 120, 130];


拉丁的传说
浏览 194回答 2
2回答

一只萌萌小番薯

仅按升序中途显示原始数组的问题,而按降序中途显示原始数组的问题是,输出将为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) {&nbsp;//slices the value of the passed in array in half, and makes 2 new arrays of it&nbsp; var arrayLength1 = a.length;&nbsp; var arrayHalf = arrayLength1 / 2;&nbsp; var firstHalf = a.slice(0,arrayHalf);&nbsp; var secondHalf = a.slice(arrayHalf);&nbsp; // sorts one array ascending and the other descending&nbsp; &nbsp;firstHalf.sort(ascendingFunction);&nbsp; &nbsp;secondHalf.sort(descendingFunction);&nbsp;//combines together the 2 arrays, already sorted one ascending and one descending&nbsp; &nbsp;var newSortedArray = firstHalf.concat(secondHalf);&nbsp;&nbsp; &nbsp;alert(newSortedArray); // the output you want&nbsp; &nbsp; }function ascendingFunction(a,b){&nbsp; &nbsp; return&nbsp; a - b&nbsp; &nbsp; }&nbsp;function descendingFunction(a,b){&nbsp; &nbsp; return&nbsp; b - a&nbsp; &nbsp; }&nbsp;var one = [10, 20, 30, 40, 50, 60, 70, 80];var two = [60, 70, 80, 90, 100, 110, 120, 130];现在您可以调用该函数并传入所需的任何数组,例如:sortArrays(one);sortArrays(two);

一只甜甜圈

您有很多语法错误-您还试图对Array自身进行排序,这是您不应该做的。您需要按升序和降序对放入的数组进行排序,然后将其写出:function compareArrays(arr1, arr2) {&nbsp; arr1.sort((a, b) => b - a);&nbsp; arr2.sort((a, b) => b - a);&nbsp; console.log(`First in ascending order: ${arr1[0]} and ${arr2[0]}`);&nbsp; arr1.sort((a, b) => a - b);&nbsp; arr2.sort((a, b) => a - b);&nbsp; 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; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答