javascript利用map,every,filter,some,reduce,sort對數組進行最優化處理

案例:app

var scoresTable=[
    {id:11,name:"小張",score:80},
    {id:22,name:"小王",score:95},
    {id:33,name:"小李",score:50},
    {id:44,name:"小劉",score:65},
    {id:55,name:"小徐",score:84}
]
一、快速獲取最高score值(採用map,Max.sum和apply)
var scores=scoresTable.map(function(item){return item.score});
var maxScore=Math.max.apply(this,scores)
console.log(maxScore)
二、是否包含不及格學生(some)
var hasFail=scoresTable.some(function(item){return item.score<60;})
console.log(hasFail)
三、求平均分(reduce)
var averageScore=scoresTable.reduce(function(a,b){return a + b.score;},0)/scoresTable.length;
console.log(averageScore)

四、按成績從高到低排序(sort)this

var score=scoresTable.sort(function(a,b){return a.score<b.score;})
console.log(score)

五、找出不及格學生(filter)spa

var failStudents=scoresTable.filter(function(item){return item.score<60;})
console.log(failStudents)

六、是否全部學生的學號都是11的倍數(every)code

var t=scoresTable.every(function(item){return item.id%11==0;})
console.log(t)
相關文章
相關標籤/搜索