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

问题描述

任务是:

在研究它的过程中,我发现一些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 s表明它正确地接收了参数(或者据我所知)已经考虑过要确定.

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.

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

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不更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:01