简体   繁体   English

Array.Filter不更新数组

[英]Array.Filter not updating array

The task is: 任务是:

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. 您将获得一个初始数组(destroyer函数中的第一个参数),后跟一个或多个参数。 Remove all elements from the initial array that are of the same value as these arguments. 从初始数组中删除与这些参数具有相同值的所有元素。

While working through it I found some Array.filter behaviour I'm struggling to understand: 在研究过程中,我发现有些Array.filter行为难以理解:

function destroyer(arr) {
  for (var i = 1; i<arguments.length; i++){
    toDelete = arguments[i];
    arr.filter(isItIn);
  }
  return arr;
}

function isItIn(item, undefined, array){
  return item!=toDelete;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

My intent here was to iterate through items 1+ of the arguments, calling arr.filter each time. 我的目的是遍历参数的1+项,每次都调用arr.filter Arr.filter then calls isItIn which checks if the currently examined item is the one I'm searching for. 然后Arr.filter调用isItIn ,它检查当前检查的项目是否是我要搜索的项目。 However, arr is being returned unchanged. 但是, arr保持不变。 When I change isItIn to: 当我将isItIn更改为:

function isItIn(item, undefined, array){
  return item==1;
}

to test, it is still unchanged, however console.log s in the original writing of isItIn show that it is receiving the arguments correctly (or so far as I've thought to determine at least. 测试,它仍然是不变的,但是console.log S IN的原始书面isItIn显示它被正确接收的参数(或者只要我认为至少确定。

Please note, I've solved the problem through another route, I'm not looking for a solution to the problem, merely an explanation of where my initial code went wrong. 请注意,我已经通过另一途径解决了该问题,我不是在寻找解决问题的方法,而只是解释我的初始代码出了什么问题。

Basically you use Array#filter and omit the result of it. 基本上,您使用Array#filter并忽略其结果。

You need to assign the result of filter to the former array. 您需要将filter的结果分配给前一个数组。

arr = arr.filter(isItIn);

 function destroyer(arr) { for (var i = 1; i < arguments.length; i++) { toDelete = arguments[i]; arr = arr.filter(isItIn); } return arr; } function isItIn(item) { return item != toDelete; } console.log(destroyer([1, 2, 3, 1, 2, 3], 2, 3)); 

You have to assign the returned array: 您必须分配返回的数组:

function destroyer(arr) {
    for (var i = 1; i<arguments.length; i++) {
        toDelete = arguments[i];
        arr = arr.filter(isItIn);
    }
    return arr;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM