Array.Filter 不更新数组 [英] Array.Filter not updating array

查看:27
本文介绍了Array.Filter 不更新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务是:

您将获得一个初始数组(第一个参数destroyer 函数),后跟一个或多个参数.移除所有初始数组中与这些值相同的元素参数.

You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.

在研究它时,我发现了一些我难以理解的 Array.filter 行为:

While working through it I found some Array.filter behaviour I'm struggling to understand:

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);

我的目的是遍历参数的 1+ 项,每次都调用 arr.filter.Arr.filter 然后调用 isItIn 来检查当前检查的项目是否是我正在搜索的项目.但是, arr 返回原样.当我将 isItIn 更改为:

My intent here was to iterate through items 1+ of the arguments, calling arr.filter each time. Arr.filter then calls isItIn which checks if the currently examined item is the one I'm searching for. However, arr is being returned unchanged. When I change isItIn to:

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

测试,它仍然没有改变,但是 isItIn 的原始编写中的 console.log 表明它正确地接收了参数(或者就我而言)想过至少确定.

to test, it is still unchanged, however console.logs 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.

请注意,我已经通过另一条途径解决了问题,我不是在寻找问题的解决方案,只是解释我的初始代码出错的地方.

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.

推荐答案

基本上你使用 Array#filter 并忽略它的结果.

Basically you use Array#filter and omit the result of it.

您需要将过滤器的结果分配给前一个数组.

You need to assign the result of filter to the former array.

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));

这篇关于Array.Filter 不更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆