Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a parameter to an Array.prototype.some() callback?

Tags:

javascript

Take a look at this piece of code:

var array = [0, 1];

var even = function(element, index, array, considerZeroEven) {
  // checks whether an element is even
  if (element === 0)
    return considerZeroEven;

  return element % 2 === 0;
};

console.log(array.some(even)); // Here I should do the trick...

Is it possible to pass to even the considerZeroEven parameter?

I saw I should use thisArg and do something dirty inside there, but I do not think this is a good idea, and looking at the polyfill on MDN it looks like it will pass only the value of the element, the index of the element, and the array object being traversed, so nothing more could be done.

like image 329
Cirelli94 Avatar asked Jan 28 '23 16:01

Cirelli94


1 Answers

You could take a closure over the wanted value of considerZeroEven and take just a function as callback without using thisArg.

var array = [0, 1],
    even = function (considerZeroEven) {
        return function(element, index, array) {
            return element === 0
                ? considerZeroEven
                : element % 2 === 0;
        };
    };

console.log(array.some(even(false)));
like image 52
Nina Scholz Avatar answered Jan 31 '23 07:01

Nina Scholz