0

I tried to delete an array part.

Did not work

delete my_array[index];

Did work

my_array.splice(index, 1);

When looking at the array it looks fine in both cases in the console.log but the first one crashed my app.

I'm not sure if Vue that I'm using are treating these differently

Why does the last one work, but not the first?

2
  • 3
    It does work, but it does something very different than splice - which comes from the fact that delete is really defined in general for objects and has no special behavior for arrays Commented Dec 6, 2020 at 16:23
  • 1
    The "special behavior" UnholySheep refers is reindexing, delete doesn't reindex the array it was used on, it leaves you with a sparse array, where as splice reindexes the array if needed. Commented Dec 6, 2020 at 16:28

3 Answers 3

2

Using the delete operator doesn't affect the length of the array, since it results in setting the element at this index as undefined.

new Vue({
  data() { return { array: [1,2,3] } },
  created() { delete this.array[1]; console.log(this.array[1]); }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

delete doesn't set the value of deleted index to undefined, instead the index is removed, causing empty slots occurring into the array.
2

Based on MDN documentation, The JavaScript delete operator removes a property from an object. Same page section Deleting array elements suggesting to use splice as you used in your 2nd case.

Alternatively delete array element

const arr = ['a', 'b', 'c'];


const deleteByIndex = (arr, index) => arr.filter((_, i) => i !== index);

console.log(deleteByIndex(arr, 1))

Comments

0

This has to do with how change detection works in Vue. At object creation getters and setters are created for each property. As soon as you update it the change will be detected.

Directly adding or deleting goes past this system and will break your app.

This is described in more detail here: https://v2.vuejs.org/v2/guide/reactivity.html

1 Comment

Oh, I did not mention but I use Vue 3 and they have fixed reactivity issues with arrays there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.