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
776 views
in Technique[技术] by (71.8m points)

javascript - How to remove element from array in forEach loop?

I am trying to remove an element in an array in a forEach loop, but am having trouble with the standard solutions I've seen.

This is what I'm currently trying:

review.forEach(function(p){
   if(p === 'u2022 u2022 u2022'){
      console.log('YippeeeE!!!!!!!!!!!!!!!!')
      review.splice(p, 1);
   }
});

I know it's getting into the if because I'm seeing YippeeeeeE!!!!!!!!!!!!! in the console.

MY PROBLEM: I know that my for loop and if logic are sound, but my attempt to remove the current element from the array is failing.

UPDATE:

Tried out Xotic750's answer, and the element is still not being removed:

Here is the function in my code:

review.forEach(function (item, index, object) {
    if (item === 'u2022 u2022 u2022') {
       console.log('YippeeeE!!!!!!!!!!!!!!!!')
       object.splice(index, 1);
    }
    console.log('[' + item + ']');
});

Here is the output where the array is still not removed:

[Scott McNeil]
[reviewed 4 months ago]
[ Mitsubishi is AMAZING!!!]
YippeeeE!!!!!!!!!!!!!!!!
[? ? ?]

So obviously it is going into the if statement as directed, but it's also obvious that the [? ? ?] is still there.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It looks like you are trying to do this?

Iterate and mutate an array using Array.prototype.splice

var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '
'));
}

var review = ['a', 'b', 'c', 'b', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
<pre id="out"></pre>

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

...