在javascript中将比较数组传递给筛选函数
我想通过将另一个数组传递给filter函数来过滤掉一个数组的值在javascript中将比较数组传递给筛选函数,javascript,arrays,Javascript,Arrays,我想通过将另一个数组传递给filter函数来过滤掉一个数组的值 x = [1,2,3]; y = [2,3]; var n = x.filter(filterByArray); function filterByArray(element, index, array, myOtherArray){ // some other code }); 将“y”传递给函数中的“myOtherArray”原型的最佳方式是什么?您不能更改回调的签名,但可以有一个单独的类,该类将另一个数组作为参数:
x = [1,2,3];
y = [2,3];
var n = x.filter(filterByArray);
function filterByArray(element, index, array, myOtherArray){
// some other code
});
将“y”传递给函数中的“myOtherArray”原型的最佳方式是什么?您不能更改回调的签名,但可以有一个单独的类,该类将另一个数组作为参数:
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);
您可以使用的第二个参数将其
此
值设置为“有用”值,例如第二个数组
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);
预期的输出是什么?\n我已经尝试了.bind(),但它对我不起作用。输出并不重要,比如说我想过滤掉重复的元素,这只是一个例子。我已经找到了不使用.filter()的方法,但我更希望使用.filter()函数。