-2

I am getting a very strange behavior while splicing the object from the array.

I have a js array with objects. I am passing it via props and populating a navigation based on it. Now when I try to delete it inside created hood it deleted half and keep half. Here is the code. Very simple

props: {
 navItems: {
  type: Array,
 },
},

In created hook I have

let nav = this.navItems
for(let j in nav){
  nav.splice(j,1)
}
console.log(nav) // print half item from the array. Shouldn't remove all?
this.nav = nav

Thank you.

Hyyan Abo Fakher
  • 3,207
  • 3
  • 18
  • 32
Hkm Sadek
  • 2,348
  • 5
  • 26
  • 62
  • Possible duplicate of [How do I remove a particular element from an array in JavaScript?](https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript) – Hyyan Abo Fakher Aug 10 '18 at 14:23

1 Answers1

3

Lets take this array:

  [1, 2, 3]

If you remove the first element you end up at:

 [2, 3]

Now you remove the second element:

[2]

And the third:

 [2]

As you can see, you actually want to splice out the first element until the array is empty:

 while(nav.length)
   nav.splice(0, 1);

or just:

  nav.splice(0, nav.length);
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • Yap you are right, but actually I need the position to delete from any position I want. So j is needed here – Hkm Sadek Aug 10 '18 at 14:25