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

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']
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值