我已经在免费代码营上学习了这门类(class)几个小时,但是,我找到了一个我不理解的解决方案,我试图在每一行上添加注释以记录我实现和理解它以供将来引用,我已经理解了一些行,但我无法理解这段代码的某些部分:
function destroyer(arr) {
// let's make the arguments part of the array
var args = Array.prototype.slice.call(arguments); // this would result into [[1, 2, 3, 1, 2, 3], 2, 3]
args.splice(0,1); // now we remove the first argument index on the array so we have 2,3 in this example
// I DO NOT UNDERSTAND THESE CODES BELOW
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
我已经检查了文档,我发现很难理解,似乎这个示例中的代码非常不同。我非常感谢您的帮助!
最佳答案
-
您不理解的代码部分中的
arr
指的是传递给destroyer
函数的第一个参数;在本例中,数组[1, 2, 3, 1, 2, 3]
arr.filter
使用Array.filter
方法创建数组的“过滤”版本,仅包含通过function(element) 定义的“测试”的值 { return args.indexOf(element) === -1; }
- 该函数使用
Array.indexOf
检查切片 args 数组(您正确识别为等于[2, 3]
)是否包含给定的元素
。由于indexOf
在未找到元素时返回 -1,因此检查该值相当于检查指定元素是否不在数组中
所有这些的结果 - 以及函数 destroy
的返回值 - 将是数组 [1, 1]
,表示数组的过滤版本传递给 destroy
,其中包含所有不等于传递给 destroy 的其他值的值。
关于javascript - 在过滤器数组上切片参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902299/