这是自由代码阵营中的一个赋值,我的问题是我的for循环不是迭代,它是一个从filter方法返回的函数,我需要循环除了初始数组[0]之外的额外参数来比较它是否匹配并删除。
这段代码的结果是1,3,1,3我希望是1,1。
function destroyer(arr) {
var p = arguments.length; // arr length
var r = arguments; //
function argScope(item) {
debugger;
for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements
if(item == r[a]) { // this is true at 1 so 2 is removed, but loop doesn't execute
return false;
} else {
return item;
}
}
}
var v = arr.filter(function(item,index,array) {
debugger;
return argScope(item); // call a function for the scope
});
return v;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3); // function call
帮助?
答案 0 :(得分:3)
在完成一次迭代后,您将从循环返回。 也许你的意思是:
for(var a =1; a<=p; a++) { // start iterate at 1, 0 is the initial array I want to remove elements
if(item == r[a]) { // r and a is not set, value is only set after
return item;
}
}
return false;
答案 1 :(得分:0)
这应该这样做:
function destroyer(arr) {
function argScope(item) {
debugger;
for (var a = 1; a < arr.length; a++)
if (item == arr[a]) return false;
return true;
}
return arr[0].filter(function(item) {
debugger;
return argScope(item); // call a function for the scope
});
}
var myArray = [1, 2, 3, 1, 2, 3];
var filteredArray = destroyer([myArray, 2, 3]);
console.log(filteredArray);