Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...