我正在尝试理解下面的“寻求和毁灭”挑战。
任务:将为您提供一个初始数组(驱逐舰函数中的第一个参数),后跟一个或多个参数。从初始数组中删除与这些参数具有相同值的所有元素。
This is the initial code below:
function destroyer(arr) {
// Remove all the values
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
经过几次(真的)尝试并查看其他人的代码后,我能够解决该任务。但是,我认为这更不幸运了。我在下面复制了我的代码,但我希望有人可以为我澄清一些事情。
下面的代码传递我是否在iterateThroughArray函数中返回val或args。那是为什么?
如果我应该将所有参数与第一个参数进行比较,那么在这段代码中我指出了什么?我一直在想我需要拼接第一个参数来比较所有其他参数,或者为参数[0]创建一个变量。非常感谢您提供的任何指导!
function destroyer(arr) {
var args = Array.from(arguments); //this also converts them to an array
var iterateThroughArr = function (val) {
if (args.indexOf(val) ===-1){
return args;
}
};
return arr.filter(iterateThroughArr);
}
答案 0 :(得分:2)
这可能听起来很多,但这是我的解释
function destroyer(arr) {
var args = Array.from(arguments); //Here arr is converted to [Array(6),2,3]
//console.log(args)
/* var iterateThroughArr = function (val) {
if (args.indexOf(val) ===-1){
return args;
}
};
return arr.filter(iterateThroughArr);
*/
// to make more clear the above code can be rewritten as below
var arr = arr.filter(function (val) {
console.log("args = "+ args + " val = " + val + " indexOf(val) " + args.indexOf(val) )
// here you are itterating through each arr val which in this case is[1,2,3,1,2,3]
// if you dont believe me uncomment the next console.log() and see the output
// console.log(val)
if (args.indexOf(val) ===-1){
// here is where the magic happens
// Now you are checking if val exisists by using a builtin method called .indexOf()
// In general, .indexOf() returns -1 if a value does not exist within an array
//Below is working example
/* var array = [1,2,3,4,5]
console.log(array.indexOf(1)) // 0 since it is located at index 0
console.log(array.indexOf(5)) // 4 since it is located at index 4
console.log(array.indexOf(10)) // -1 since it does not exisit
*/
// Therefore, if value passes the above if statement
//then that means it doesnot exisit on args([Array(6),2,3])
//which as a result will be included on the filtered array
return args;
}
});
return arr;
}
var val = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//console.log(val)
基本上,您需要了解的是过滤器的工作原理以及.indexOf的工作原理。 有关更多详细信息,请访问Mozilla文档:.indexOf()和.filter()
答案 1 :(得分:0)
尝试一下:
function destroyer(arr) {
// arr1 is equal to the array inside arr
var arr1 = arr.slice(arguments);
// arr2 becomes an array with the arguments 2 & 3
var arr2 = Array.prototype.slice.call(arguments, 1);
// this function compares the two and returns an array with elements not equal to the arguments
return arr1.concat(arr2).filter(function (item) {
return !arr1.includes(item) || !arr2.includes(item)
})
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);