Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

javascript - 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. 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:

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. 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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...