JQuery grep gripes

According to the $.grep() documentation, I would have thought that the code below would print 2 . But instead, it prints 0,1,2 . See this script . Am I going to loco?

 var arr = [0, 1, 2]; $.grep( arr, function(n,i) { return n > 1; }); $('body').html( arr.join() ); 
+4
source share
2 answers

$.grep returns a new array - it does not modify your existing one.

Do you want to

 arr = $.grep( arr, function(n,i) { return n > 1; }); 

Check out $. grep docs for more information

+6
source

You are missing the key part.

"Description: Finds array elements that satisfy the filter function. The original array does not change."

 var newArray = $.grep( arr, function(n,i) { return n > 1; }); $('body').html( newArray.join() ); 
+3
source

Source: https://habr.com/ru/post/1388041/


All Articles