Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element of Javascript Array with safe method?

I have a code :

myarray[150] = 'a';
myarray[80] = 'b';
myarray[122] = 'c';

And then :

myarray.splice(80, 1);
myarray[80] = 'b';

The result of my code above on my application is :

[150] = 'a'; [80] = 'b'; [121] = 'c';

I don't understand why c value have 121 as index. Can anyonen explain what's wrong with my code?

like image 832
Mr. Mike Avatar asked Oct 17 '25 05:10

Mr. Mike


2 Answers

This line of code removes one element of the array at index 80. Thus, all elements after 80 would be shifted down one index:

myarray.splice(80, 1);
like image 104
tonythewest Avatar answered Oct 18 '25 22:10

tonythewest


You have to use:

delete myarray[80]

for safe delete

like image 37
Mayki Nayki Avatar answered Oct 18 '25 20:10

Mayki Nayki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!