1、filter是数组原型上的方法,Array.prototype.filter
2、Array.prototype.filter函数有两个参数:
参数1:是回调函数
参数2:用来改变第1个参数(函数)中的this指向,选填的参数
3、参数1说明
var arr = [2,3,4];
var newArr = arr.filter(function(elem, index, array){
//回调函数的参数说明:
//第1个参数是filter遍历到的元素
//第2个参数是filter遍历到的元素的索引
//第3个参数是遍历的数组
//回调函数的返回值:
//函数返回true时,元素elem会装到newArr中。函数返回false时,elem不会装到newArr
//中。newArr是新的数组与arr没有关系
});
示例:
var arr = [2,3,4];
var newArr = arr.filter(function(elem, index, array){
if(elem>3){
return true;
}
});
console.log(newArr);
输出
[4]
4、参数2示例
var arr = [2,3,4];
var newArr = arr.filter(function(elem, index, array){
console.log(this);
},{name:'change this'});
输出:
{name: 'change this'}
{name: 'change this'}
{name: 'change this'}