Home > php教程 > PHP开发 > Use $.grep() method

Use $.grep() method

高洛峰
Release: 2016-12-13 14:44:03
Original
1589 people have browsed it

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(',');
Copy after login

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"]
Copy after login

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"]
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template