I have the following array:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
I use delete example[0]; and am left with the following result:
var example = [
1: function() { /* goodbye */ }
];
Is there a better solution than delete? Or is there a simple way to fix the indexes in the array? (I have jQuery at my disposal)
Edit: I fixed the example array. The indexes were there for the example.
As example is an array, instead of delete, you can use .splice [MDN]:
example.splice(0, 1);
But if examples is actually an object, you'd have to use delete and iterate over all properties and "rename" them. Though it's probably easier to use an array instead.
The reason why you get this result with delete is that you are removing the property '0' from the underlying object and the property '1' still exists. You are basically operating on a lower level.
Another problem with gaps in the indexes is that array.length will always return the the highest index + 1 and not the actual number of values in the array. So after deleting the element, example.length would still be 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With