【发布时间】:2016-11-16 11:14:40
【问题描述】:
我正在学习在线 JavaScript 课程,我对其中一项任务感到好奇:
我们提供了一个初始数组(销毁函数中的第一个参数),然后是一个或多个参数。我们必须从初始数组中删除与这些参数具有相同值的所有元素。
这是我的解决方案,但它不起作用:
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);
感谢您的提醒!
【问题讨论】:
-
filter中的函数需要返回一些值。如果为真(例如true),则保留该元素,如果为假(例如false),则将其删除。您只会返回false或undefined(自动),这是错误的。 -
如果要保留元素,传递给
filter方法的函数必须返回true。如果它只返回false,它将删除所有内容。 Not 返回值被视为返回false。
标签: javascript arrays