Jens Törnell
Jens Törnell

Reputation: 24778

Why does delete not work on array in javascript?

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?

Upvotes: 0

Views: 721

Answers (3)

T. van den Berg
T. van den Berg

Reputation: 364

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

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

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))

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28424

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>

Upvotes: 2

Related Questions