我想从作为arguments
传递的函数destroyer
中传递的array
中删除所有arguments
。
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments); //turns arguments into arrays
function checkArgs() {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < args.length; j++) {
if (arr[i] == args[j]) {
delete arr[i];
}
}
}
}
return arr.filter(checkArgs);
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); //Remove 2nd, 3rd, etc arguments from first argument...??
.filter
回调要求您return
过滤结果中应包含的内容。
来自MDN:
返回值
包含通过测试的元素的新数组。如果没有 元素通过测试,将返回一个空数组。
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments); // turns arguments into arrays
function checkArgs() {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < args.length; j++) {
if (arr[i] == args[j]) {
delete arr[i];
}
}
}
// You have to return something in the filter callback
return arr;
}
return arr.filter(checkArgs);
}
//remove 2nd, 3rd, etc arguments from first argument
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
console.log(destroyer([1, 2, 3, 1, 2, 3], 3));
.filter
需要一个return
值作为筛选值。而且argumnents
还包含位置0
处的array arr
,因此您必须从位置1
开始。
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments); //turns arguments into arrays
function checkArgs() {
for (var i = 0; i < arr.length; i++) {
for (var j = 1; j < args.length; j++) {
if (arr[i] == args[j]) {
delete arr[i];
}
}
}
return arr;
}
return arr.filter(checkArgs);
}
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));
这是过滤器的稍微简化的版本。还有其他方法可以优化这一点。这是假设一个从 0 开始的索引。
function destroyer(arr) {
var args = Array.prototype.slice.call(arguments); // turns arguments into arrays
return args[0].filter(function(item, index) {
return args.indexOf(index) < 0;
});
}
//remove 2nd, 3rd, etc arguments from first argument
console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3));