Home  >  Article  >  php教程  >  Use $.grep() method

Use $.grep() method

高洛峰
高洛峰Original
2016-12-13 14:44:031516browse

I have never used the $.grep() method before. The $.grep() method filters an array according to certain conditions, so using the $.grep() method can filter out the results we want from the array. Let’s take an example. For example, there is an array named nums:

var nums = '1,2,3,4,5,jQuery,CSS,5'.split(',');

It can be seen that there are numbers and strings in the array. If we want to find the strings in it, we can directly use the $.grep() method to To complete this task, as follows:

nums = $.grep(nums, function (num, index) {
    // num = 数组元素的当前值  
    // index = 当前值的下标
    return isNaN(num);});console.log(nums); //结果为: ["jQuery", "CSS"]

We can easily think of the $.map() method. The $.map() method can convert one array into another array, so this task can also be completed using the $.map() method. , as follows:

nums = $.map(nums, function (num, index) {
    //和$.grep() 的区别
    //return isNaN,得到结果为:[true, true]
    return isNaN(num) ? num : null;});console.log(nums); // ["jQuery", "CSS"]

This article briefly introduces the use of the $.grep() method, and also compares the $.map() method. It can be seen that proper use of jQuery built-in methods can simplify our program.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn