简体   繁体   中英

passing parameter to jquery $.grep

If I have this pice of code which checks is something already exist inside array

var array = [ 1, 5, 12, 31, 7, 69 ];

var array = $.grep(array, function(n, i) {
  return (n == 112);
});

alert(array.length);

my question is simple one: How can I pass variable to this grep function and to use it instead of hardcoded 112 value inside expression?

You can just pass a variable from the outside. JavaScript's lexical scope allows for variables from the outside scope to be passed into deeper functions.

http://jsfiddle.net/ag1djcjm/

var array = [ 1, 5, 12, 31, 7, 69];
var code = 112;

// No need to declare variables twice
array = $.grep(array, function(n, i) {
  return (n == code);
});

alert(array.length);

Try like this

var array = [ 1, 5, 12, 31, 7, 69 ];

var val=112;
// remove var from here it'll re-declare same variable
array = $.grep(array, function(n, i) {
  return (n == val);
});

alert(array.length);

JSFIDDLE

You can do it by javascript's .filter() also

Like this

var array = [ 1, 5, 12, 31, 7, 69 ];
var val=112;
array = array.filter(function(n) { return n == val; });
alert(array.length);

JSFIDDLE

Just define the value you need to filter before calling $.grep function. See example below

var array = [1, 5, 12, 31, 7, 69],
    filterValue = 5;

var newArray = $.grep(array, function (n, i) {
    return n == filterValue;
});

Since you're redefining the array, I created a new variable newArray and assigned filtered values to that, but you can still assign it to array variable.

Code:

function filter ( data, val ) {
    return $.grep(data, function ( n, i ) {
        return (n == val);
    });
}

Test:

var array = [ 1, 5, 12, 31, 7, 69];
var test = filter(array, 112);
alert(test.length);

So, what you're basically trying to do, it determine if an array of numbers contains a certain number (variable).

There's no need to over-complicate this with grep. Just use indexOf :

 var array = [ 1, 5, 12, 31, 7, 69 ], search = 112, hasNumber = array.indexOf(search) !== -1; // Using this so that it's visible in the snippet. document.body.textContent = hasNumber; 

Could create a function outside of $.grep() , to be called for each item in array ; could also pass additional parameters to function . Also try defining different variable names for input array , resulting array

var array = [ 1, 5, 12, 31, 7, 69 ], num = 112
, compare = function(n, i) { return n === num }

var res = $.grep(array, compare);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM