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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…