JS Basic (2) filter filter ()

Source: Internet
Author: User

Filter is also a common operation, it is used to Array filter out some of the elements, and then return the remaining elements.

and map() Similarly, Array filter() a function is also received. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether true false the element is persisted or discarded based on the return value.

For example, in one Array , delete an even number, keep only the odd number, and you can write:

var arr = [1, 2, 4, 5, 6, 9, 10, 15];var r = arr.filter(function (x) { return x % 2 !== 0;});r; // [1, 5, 9, 15]

Delete the Array empty string in one, so you can write:

var arr = [‘A‘, ‘‘, ‘B‘, null, undefined, ‘C‘, ‘ ‘];var r = arr.filter(function (s) { return s && s.trim(); // 注意:IE9以下的版本没有trim()方法});r; // [‘A‘, ‘B‘, ‘C‘]

filter()the key to using this higher-order function is to implement a "filter" function correctly.

callback function

filter()The received callback function can actually have multiple parameters. Usually we use only the first parameter, which represents an Array element. The callback function can also receive two additional parameters, representing the location of the element and the array itself:

var arr = [‘A‘, ‘B‘, ‘C‘];var r = arr.filter(function (element, index, self) { console.log(element); // 依次打印‘A‘, ‘B‘, ‘C‘ console.log(index); // 依次打印0, 1, 2 console.log(self); // self就是变量arr return true;});

Using filter , can subtly remove Array the repeating elements:

JS Basic (2) filter filter ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.