简体   繁体   English

我可以将参数传递给Array.prototype.some()回调吗?

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

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? 是否可以传递给thinkZeroEven参数?

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. 我看到我应该使用thisArg并在其中进行一些肮脏的操作,但是我认为这不是一个好主意,而在MDN上查看polyfill似乎只会传递元素的值,元素的索引,并且遍历了数组对象,因此无法执行其他操作。

You could take a closure over the wanted value of considerZeroEven and take just a function as callback without using thisArg . 你可以采取封闭过的通缉值considerZeroEven ,并采取只是一个函数回调不使用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))); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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