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.