Use of filter()

The use of js filter

1. filter()The method creates a new array, and the elements in the new array are checked by checking all elements in the specified array that meet the conditions .

First of all: the filter() method is to filter the array, right? I think there are a lot of arrays to be processed during development; secondly: we need to know
one thing is filter() 不会对空数组进行过滤, and at the same time 不会改变原数组;
finally: list a parameter surface;

parameter describe
currentValue Mandatory, representing the current value
index Optional, representing the subscript of the element, index
arr Optional, representing the array object to which the current element belongs

Then give a few simple examples:
1. Common odd and even numbers?

var arr = [1, 2, 4, 5, 6, 9];
var oddNum = arr.filter(function (x) {
    
    
    return x % 2 !== 0;   //返回的是奇数
})

insert image description here
2. Combined with multi-parameter use;

var arr = ['A', 'B', 'C'];
arr.filter(function (text, index, self) {
    
     
   console.log(text); // 'A', 'B', 'C'
   console.log(index); // 0, 1, 2
   console.log(self); // self就是变量arr
});

Guess you like

Origin blog.csdn.net/weixin_45103130/article/details/127011683