我正在参加在线 JavaScript 类(class),我对其中一项任务感到好奇:
我们提供了一个初始数组(破坏函数中的第一个参数),后跟一个或多个参数。我们必须从初始数组中删除与这些参数具有相同值的所有元素。
这是我的解决方案,但它不起作用:
function destroyer(arr) {
// Separating the array from the numbers, that are for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// This is just to check if we got the right numbers
console.log(filterArr);
// Setting the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
}
}
// Let's check what has been done
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
我找到了解决方案,但对我来说没有任何意义,这就是我发布这个问题的原因;你能告诉我为什么下面的代码有效吗:
function destroyer(arr) {
// Separating the array from the numbers, that are for filtering;
var filterArr = [];
for (var i = 1; i < arguments.length; i++) {
filterArr.push(arguments[i]);
}
// This is just to check if we got the right numbers
console.log(filterArr);
// Setting the parameters for the filter function
function filterIt(value) {
for (var j = 0; j < filterArr.length; j++) {
if (value === filterArr[j]) {
return false;
}
// This true boolean is what makes the code to run and I can't // understand why. I'll highly appreciate your explanations.
}
return true;
}
// Let's check what has been done
return arguments[0].filter(filterIt);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
感谢您的提醒!
最佳答案
您可以通过使用 Array.prototype.reduce()
来使用相对简单的代码完成相同的工作,如下所示;
ES6
var destroyer = (a,...f) => a.reduce((p,c) => f.includes(c) ? p : p.concat(c),[]);
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
或者在 ES5 中
function destroyer(a){
var f = Array.prototype.slice.call(arguments,1);
return a.reduce(function(p,c){
return f.indexOf(c) !== -1 ? p : p.concat(c);
},[]);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
关于JavaScript 过滤器数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40630734/