问题
The task is:
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
While working through it I found some Array.filter behaviour I'm struggling to understand:
function destroyer(arr) {
for (var i = 1; i<arguments.length; i++){
toDelete = arguments[i];
arr.filter(isItIn);
}
return arr;
}
function isItIn(item, undefined, array){
return item!=toDelete;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
My intent here was to iterate through items 1+ of the arguments, calling arr.filter
each time. Arr.filter
then calls isItIn
which checks if the currently examined item is the one I'm searching for. However, arr
is being returned unchanged. When I change isItIn
to:
function isItIn(item, undefined, array){
return item==1;
}
to test, it is still unchanged, however console.log
s in the original writing of isItIn
show that it is receiving the arguments correctly (or so far as I've thought to determine at least.
Please note, I've solved the problem through another route, I'm not looking for a solution to the problem, merely an explanation of where my initial code went wrong.
回答1:
Basically you use Array#filter and omit the result of it.
You need to assign the result of filter to the former array.
arr = arr.filter(isItIn);
function destroyer(arr) {
for (var i = 1; i < arguments.length; i++) {
toDelete = arguments[i];
arr = arr.filter(isItIn);
}
return arr;
}
function isItIn(item) {
return item != toDelete;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
回答2:
You have to assign the returned array:
function destroyer(arr) {
for (var i = 1; i<arguments.length; i++) {
toDelete = arguments[i];
arr = arr.filter(isItIn);
}
return arr;
}
来源:https://stackoverflow.com/questions/41802480/array-filter-not-updating-array