js数组常用操作方法汇总——filter

来源:互联网 发布:如何成为淘宝砍价师 编辑:程序博客网 时间:2024/06/05 18:36

Array.filter

filter()的作用是返回某一数组中满足条件的元素,该方法返回的是一个新的数组

示例代码

返回文字长度大于6的数组元素

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"]var longWords = word.filter(function(word){        return word.length > 6    })// Filtered array longWords is ["exuberant", "destruction", "present"]

ES 6

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"]    var longWords = words.filter(word => word.length>6))// Filtered array longWords is ["exuberant", "destruction", "present"]

语法规则(Syntax)

var newArray = arr.filter(callback[,thisArg])
或者
array.filter(function(currentValue,index,arr), thisValue)

参数(Parameters)

callback:必须,数组中的每一个元素都会执行该函数,满足条件的元素被返回至新数组内,未满足条件的被忽略。该函数默认有三个参数。
element(必选):当前元素的值
index(可选): 当前元素的索引
array(可选):当前元素所属的数组

thisValue(可选):该值在callback被执行的时候使用,该值会被用作callback的this值。【If a thisArg parameter is provided to filter, it will be used as the callback’s this value. 】

返回值

filter()返回一个由满足条件的元素组成的新的数组

Example

1、该例子选出数组中大于等于10的元素

function isBigEnough(value){    return value >= 10}var filtered = [12,5,8,16,125,98].filter(isBigEnough)// filtered is [12, 130, 44]

2、该例子选出json中所有id为数字的元素

var arr = [  { id: 15 },  { id: -1 },  { id: 0 },  { id: 3 },  { id: 12.2 },  { },  { id: null },  { id: NaN },  { id: 'undefined' }];var invalidEntries = 0;function isNumber(obj){    return obj !== 'undefined' && typeof(obj) === 'Number' && !isNaN(obj);}function filterById(item){    if(isNumber(item.id)){        return true;    }    invalidEntries++;    return false}var arrId = arr.filter(filterById)console.log(arrId);// arrId is [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]

3、该例子根据查询条件筛选出满足条件的元素

var fruits = ['apple','banana','mango','grapes','orange'];function fruitsItem(query){    return fruits.filter(function(el){        return el.toLowerCase().indexOf(query.toLowerCase()) > -1    })}console.log(fruitsItem('ap'));// ['apple', 'grapes']console.log(fruitsItem('an'));// ['banana', 'mango', 'orange']
原创粉丝点击