es6數(shù)組新增6個(gè)方法
1.map (映射)1個(gè)對(duì)一個(gè) 進(jìn)去什么最后return 什么 不會(huì)改變?cè)瓟?shù)組,返回一個(gè)新的數(shù)組,對(duì)應(yīng)參數(shù):item 每次的值扒磁,當(dāng)前索引庆揪,原來(lái)數(shù)組 arr
例子:
成績(jī)對(duì)應(yīng)等級(jí)
let arr =[22,55,67,33,99,70];
let result = arr.map((item,index,arr)=>{
return item>60?'及格':'不及格';
})
console.log(result)
2.reduce (匯總) 1堆對(duì)一個(gè) 求和或者求平均數(shù)
let store = [22,44,33,56,70,83,80]
let total = store.reduce((temp,item,index)=>{
//temp是每次的臨時(shí)變量是第n次和第n+1次的臨時(shí)和,item是每次要往上加的值妨托,index是每次循環(huán)的index
console.log(temp,item,index)
return temp+item;
})
console.log(total)
要是求平均數(shù) 就應(yīng)該再最后一次時(shí)用總數(shù)除以數(shù)組的長(zhǎng)度缸榛。
let store = [22,44,33,56,70,83,80]
let total = store.reduce((temp,item,index)=>{
//temp是每次的臨時(shí)變量是第n次和第n+1次的臨時(shí)和,item是每次要往上加的值兰伤,index是每次循環(huán)的index
console.log(temp,item,index)
if(index!=arr.lenth-1){//不是最后一次
return temp+item;
}else{//是最后一次
return (temp+item)/arr.length;
}
})
console.log(total)
3.filter 過(guò)濾器 通過(guò)返回true或者false來(lái)確認(rèn)最終的結(jié)果
let num = [2,4,76,87,35,66];
let result = num.filter(item=>item%3===0)
console.log(result);
4.forEach 循環(huán) (迭代)
//forEach遍歷數(shù)組内颗,無(wú)返回值敦腔,不改變?cè)瓟?shù)組符衔,僅僅只是遍歷
let arr = [2,3,4,5]
arr.forEach(item=>console.log(item))
5.every
let arr = [1,2,3,4];
let flag= arr.every((item,index,arr) =>item > 1 //結(jié)果為false
)
//遍歷數(shù)組每一項(xiàng)纸厉,每一項(xiàng)返回true,則最終結(jié)果為true。當(dāng)任何一項(xiàng)返回false時(shí)沃缘,停止遍歷,返回false水慨。不改變?cè)瓟?shù)組
6.some
var arr = [1,2,3,4];
let num =arr.some((item,index,arr) => {
console.log(item)
return item > 1 //結(jié)果為false
})
console.log(num)
//遍歷數(shù)組每一項(xiàng)晰洒,有一項(xiàng)返回true,就返回true砌滞,當(dāng)任何一項(xiàng)返回true時(shí)绊茧,則停止遍歷按傅,返回true;
以上6個(gè)方法均為ES6語(yǔ)法况芒,IE9及以上才支持。不過(guò)可以通過(guò)babel轉(zhuǎn)意支持IE低版本压汪。
以上均不改變?cè)瓟?shù)組。
some穿香、every返回true、false洒宝。
map、filter返回一個(gè)新數(shù)組将宪。
reduce讓數(shù)組的前后兩項(xiàng)進(jìn)行某種計(jì)算印蔗,返回最終操作的結(jié)果。
forEach 無(wú)返回值。