如何使用JS排序

具体如下所示
张三考试成绩为98,李四为65,王五为75
如何按分数排序并显示其分数和姓名。请问用JS该如何从高到低排序呢?非常感谢。

繁星点点滴滴
浏览 589回答 4
4回答

青春有我

let students = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; name:"张三",&nbsp; &nbsp; &nbsp; &nbsp; score:98&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; name:"李四",&nbsp; &nbsp; &nbsp; &nbsp; score:65&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; name:"王五",&nbsp; &nbsp; &nbsp; &nbsp; score:75&nbsp; &nbsp; }];students.sort((a,b)=>{&nbsp; &nbsp; return b.score-a.score;});输出:[&nbsp; &nbsp; {name: "张三", score: 98},&nbsp; &nbsp; {name: "王五", score: 75},&nbsp; &nbsp; {name: "李四", score: 65}]更新//使用split("||")可以分割"||"两侧字符串,得到一个数组。数组第一项为姓名,第二项为分数//按分数排序score.sort((a,b)=>{&nbsp; &nbsp; scoreA = +a.split("||")[1];&nbsp; &nbsp; scoreB = +b.split("||")[1];&nbsp; &nbsp; return scoreB - scoreA;});//输出姓名和分数for(var i = 0;i < score.length;i++){&nbsp; &nbsp; //姓名&nbsp; &nbsp; console.log(score[i].split("||")[0]);&nbsp; &nbsp; //分数&nbsp; &nbsp; console.log(score[i].split("||")[1]);}这个问题其实挺基础的,提问前先百度吧~

森栏

数组 就用sort 排序,看你数据格式而确定怎么做最好

慕盖茨4494581

arr.sort((a,b)=>{&nbsp; &nbsp; return b-a})边学边看书啊

慕姐4208626

var testList=[......]function sortList(a, b) {&nbsp; &nbsp; return b.score - a.score}testList.sort(sortList)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript