Array对象属性详解6-filter

Array对象属性

Array对象属性六( filter() - ES6)

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。filter() 不会对空数组进行检测。filter() 不会改变原始数组。

语法

array.filter(function(currentValue,index,arr), thisValue)

参数 描述
function(currentValue,index,arr) 必须。函数,数组中的每个元素都会执行这个函数
currentValue,index,arr 函数参数描述:1、currentValue:必须。当前元素的值;2、index 可选。当前元素的索引值 ; 3、arr 可选。当前元素属于的数组对象
thisValue 可选。前面函数的this,如果省略了 thisValue ,“this” 的值为 “undefined”
var ages = [32, 33, 16, 40];
function checkAdult(age, index, arr) {
    console.log(index);
    console.log(arr);
    console.log(this);
    return age >= 18;
}
console.log( ages.filter(checkAdult,this) )   
// 0 1 2 3
// (4) [32, 33, 16, 40](被比较的数组)
// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, 
//close: ƒ, frames: Window, …} //this
// [32, 33, 40]

资料引用:
JavaScript Array filter() 方法-菜鸟教程

猜你喜欢

转载自blog.csdn.net/siwangdexie_copy/article/details/83186435