Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中将比较数组传递给筛选函数_Javascript_Arrays - Fatal编程技术网

在javascript中将比较数组传递给筛选函数

在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”原型的最佳方式是什么?您不能更改回调的签名,但可以有一个单独的类,该类将另一个数组作为参数:

我想通过将另一个数组传递给filter函数来过滤掉一个数组的值

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()函数。