filter(过滤器)函数
语法:var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
调用该数组函数返回一个,满足条件的新数组.
1.callback是一个回调函数,可以传递三个参数,element表示遍历到的数组中的每一个元素,index表示的是元素下标,array表示原数组
2.thisArg表示传递给callback函数的新的this指向,默认情况下callback函数内部的this指向是window。
- 解释thisArg,例如:
var arr = [1,23,67,12]
var that
var res=arr.filter(function(){
that=this
return item>11
},['rr'])
console.log(that)
输出的that结果是 rr
使用filter函数获取id>10的属性:
var a = [
{ id: 15,name:'aa' },
{ id: 1,name:'bb' },
{ id: 5,name:'cc' },
{ id: 35,name:'dd' },
{ id: 65,name:'ee' },
];
var newA=a.filter(function(item,index,a){
return item.id > 15
})
console.log(newA)
//打印结果:
//(2) [{…}, {…}]
// 0: {id: 35, name: 'dd'}
// 1: {id: 65, name: 'ee'}
// length: 2
// [[Prototype]]: Array(0)
map(映射)函数
语法:var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
map() 方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数(callback函数)后的返回值。
1.callback函数可传三个参数,currentValue数组中当前处理的元素,index数组中当前处理元素的下标值,array map处理的数组
2.thisArg作用同上filter.
使用map函数让数组每个元素*3实例:
var y=[1,4,6,8,9]
var newY=y.map(function(item){
return item*3
})
console.log(newY)
//输出结果:
// (5) [3, 12, 18, 24, 27]
// 0: 3
// 1: 12
// 2: 18
// 3: 24
// 4: 27
// length: 5
// [[Prototype]]: Array(0)
reduce(汇总)函数
语法:arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
该方法用于 汇总数组中的值:
1.callback执行数组中每一个值(如果没有提供initialValue则第一个值除外)的函数,包含四个参数:accumulate累加器累计回调的返回值,他是上一次的累加值,currentValue 数组中正在处理的元素,index正在处理的元素的索引(如果没有提供initialValue则索引号从0开始,否则从1开始),array 调用reduce的数组
2.initialValue是可选值,是第一次调用callback函数的第一个参数值。如果没有提供初始值,那么将使用数组中的第一个元素。没有初始值的空数组调用reduce函数会报错
var t=[]
var T=t.reduce(function(acc,item){
return acc+item
})
console.log(T)
报错:Uncaught TypeError: Reduce of empty array with no initial value at Array.reduce (<anonymous>) at
使用reduce函数求和数组实例:
var t=[12,50,10]
var T=t.reduce(function(acc,item){
return acc+item
},0)
console.log(T)
//输出结果:72
forEach(遍历)
语法: arr.forEach(callback(currentValue [, index [, array]])[, thisArg]) 返回值undefined
find(查找)函数
语法:arr.find(callback(element,index,arr)[, thisArg])
返回数组中第一个满足函数条件的值,如果没有返回undefined
findIndex(查找)函数
语法:arr.findIndex(callback(element,index,arr)[, thisArg])
返回数组中第一个满足函数条件的索引,如果没有返回-1