數(shù)組的reduce
reduce()方法接收一個函數(shù)callback作為累加器偎肃,數(shù)組中的每個值(從左到右)開始合并惧蛹,最終為一個值浙踢。
array.reduce(callback,[initialValue])
function callback(preValue,curValue,index,array){}
preValue: 上一次調(diào)用回調(diào)返回的值婴梧,或者是提供的初始值(initialValue)
curValue: 數(shù)組中當前被處理的數(shù)組項
index: 當前數(shù)組項在數(shù)組中的索引值
array: 調(diào)用 reduce()方法的數(shù)組
var ar=[-1,2,5,-2]
let obj = ar.reduce(function(o,b,c,d){
console.log(o, b, c, d)
return b+o
},10)
console.log(obj)
[站外圖片上傳中...(image-7cadad-1564041810829)]
var ar=[-1,2,5,-2]
let obj = ar.reduce(function(o,b,c,d){
console.log(o, b, c, d)
return b+o
})
console.log(obj)
[站外圖片上傳中...(image-ed4c13-1564041810829)]
reduceRight
reduceRight和reduce功能一樣但是他是從右到左累加
var ar=[-1,2,5,-2]
let obj = ar.reduceRight(function(o,b,c,d){
console.log(o, b, c, d)
return b+o
})
console.log(obj)
[站外圖片上傳中...(image-b5cd85-1564041810829)]
filter
filter() 方法創(chuàng)建一個新的數(shù)組穗椅,新數(shù)組中的元素是通過檢查指定數(shù)組中符合條件的所有元素脆烟。
注意: filter() 不會對空數(shù)組進行檢測。
注意: filter() 不會改變原始數(shù)組房待。
array.filter(function(currentValue,index,arr), thisValue)
currentValue 必須邢羔。當前元素的值
index 可選。當前元素的索引值
arr 可選桑孩。當前元素屬于的數(shù)組對象
thisValue 可選拜鹤。對象作為該執(zhí)行回調(diào)時使用,傳遞給函數(shù)流椒,用作 "this" 的值敏簿。如果省略了 thisValue ,"this" 的值為 "undefined"
const students = [{
name: '張三',
score: 73,
sex: 'male',
}, {
name: '劉麗',
score: 62,
sex: 'female'
}, {
name: '李四',
score: 93,
sex: 'male'
}, {
name: '王五',
score: 100,
sex: 'male'
}];
const isExcellent = student => student.score > 80;
const excellentStudentNames = students => students.filter(isExcellent)
[站外圖片上傳中...(image-5823c7-1564041810829)]
splice
刪除數(shù)組里面的元素
let a = [1,2,3];
let b = a.splice(2,1)
刪除數(shù)組里面的第2個的第一位起的元素; 結(jié)果a為[1,2], b為[3]