通过参数过滤参数,为什么这不起作用



我想从作为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));

最新更新