Reputation: 123
I have the following piece of code:
function destroyer(arr) {
for(var i=1; i<arguments.length; i++){
var kill = arguments[i];
arr = arr.filter(function(x){return x != kill;});
}
return arr;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
It removes the elements from an array which equal the optional arguments. This code gives [1,1] as I expect.
But if I change the 4th line to
arr = arr.filter(function(x){return x != arguments[i];});
I get [1,2,3,1,2,3] instead, when I expect [1,1]. Why is that the case?
Upvotes: 0
Views: 29
Reputation: 53198
Because when you use arguments
within the anonymous function, you're accessing arguments of that function, not destroyer()
.
You will need to copy the arguments
of destroyer()
, preferably before your loop as follows:
function destroyer(arr) {
var args = arguments;
for(var i=1; i < args.length; i++)
{
arr = arr.filter(function(x){return x != args[i];});
}
return arr;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Alternatively, an arrow function can also be used to achieve the same functionality:
function destroyer(arr) {
for(var i=1; i<arguments.length; i++){
arr = arr.filter(x => x != arguments[i]);
}
return arr;
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
Upvotes: 2