我想通过将另一个数组传递给过滤器函数来过滤掉数组的值。
x = [1,2,3];
y = [2,3];
var n = x.filter(filterByArray);
function filterByArray(element, index, array, myOtherArray){
// some other code
});
在函数中将“y”传递给“myOtherArray”原型的最佳方法是什么?
答案 0 :(得分:1)
您无法更改回调的签名,但您可以拥有一个单独的类,将另一个数组作为参数:
function MyFilter(otherArray) {
this.otherArray = otherArray;
}
MyFilter.prototype.filterByArray = function(element, index, array) {
// you can use this.otherArray here
};
然后:
x = [1,2,3];
y = [2,3];
var myFilter = new MyFilter(y);
var n = x.filter(myFilter.filterByArray);
答案 1 :(得分:1)
您可以使用.filter(callback[, thisArg])
的第二个参数将其this
值设置为“有用”,例如您的第二个数组
function filterByArray(element, index, array) {
return this.lookup.indexOf(element) > -1; // this.lookup == y
};
var x = [1,2,3],
y = [2,3];
var result = x.filter(filterByArray, {lookup: y});
console.log(result);