Forbes magazine logo Ranked Best Coding Bootcamps 2023

(一个关于filter的问题)实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值

Altcademy Team wrote on 7 February 2018

问题是:实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值。

一开始是这样的:
function destroyer(arr) { for(var i=1;i<arguments.length;i++){ arr=arr.filter(function(x){return x!==arguments[i];}); } return arr; } destroyer([1, 2, 3, 1, 2, 3], 2, 3); //结果返回了原数组

后来声明了一个变量存储argumetns[i]就没问题了,Why?
function destroyer(arr) { for(var i=1;i<arguments.length;i++){ var number=arguments[i]; arr=arr.filter(function(x){return x!==number;}); } return arr; } destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Hi @GreatAuk, you can have a look at the following repl https://repl.it/Cn6r

What is happening is the first arguments is the arguments of the destroyer function, the second arguments is the arguments of the filter callback function.

function destroyer(arr) { for(var i=1;i<arguments.length;i++){ console.log('arguments1', arguments) // => arguments1 { '0': [ 1, 2, 3, 1, 2, 3 ], '1': 2, '2': 3 } arr = arr.filter(function(x){ console.log('arguments2', arguments); // => argument2 { '0': 1, '1': 0, '2': [ 1, 2, 3, 1, 2, 3 ] } return x!==arguments[i]; }); } return arr; } destroyer([1, 2, 3, 1, 2, 3], 2, 3); //结果返回了原数组

But you actually want to compare x with the elements of arr so you have to assign it for each step of the for loop.

for(var i=1;i<arguments.length;i++){ var number = arguments[i]; // assign argument element to number so it can be used in the filter callback function arr = arr.filter(function(x){return x!==number;}); }

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #89

Enroll for May 6th, 2024