What is the difference between using the
delete
operator on the array element and using the Array.splice
method?
For example:
myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // or myArray.splice (1, 1);
Why even have the splice method if I can delete array elements as I can with objects?
The answer
These are different things that have different purposes.
splice
is table-specific and, when used for deletion, removes table entries and moves all previous entries to fill the gap. (It can also be used to insert entries, or both at the same time.) splice
will change the length
of the array (assuming it is not a non-op call: theArray.splice(x, 0)
) .delete
is not table-specific; it is designed to be used on objects: it deletes a property (key-value pair) of the object on which you use it. It only applies to arrays because standard arrays (for example, untyped) in JavaScript are not really arrays *, they are objects with special processing for some properties, such as those whose names are " indexes of arrays "defined as string names" ... whose numerical value is between +0 ≤ i < 2^32-1
") and the length
. When you use delete
to delete an array entry, all it does is delete the entry; it does not move subsequent entries to fill the vacuum, so the array becomes "sparse" (some entries are missing). It has no effect on the length
.
Some of the current answers to this question incorrectly indicate that using
delete
"sets the entry to undefined
". It's not correct. It removes the entry (property) entirely, leaving a void.
Let's use code to illustrate the differences:
console.log("Using `splice`:"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 a.splice(0, 1); console.log(a.length); // 4 console.log(a[0]); // "b"
console.log("Using `delete`"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 delete a[0]; console.log(a.length); // still 5 console.log(a[0]); // undefined console.log("0" in a); // false console.log(a.hasOwnProperty(0)); // false
console.log("Setting to `undefined`"); var a = ["a", "b", "c", "d", "e"]; console.log(a.length); // 5 a[0] = undefined; console.log(a.length); // still 5 console.log(a[0]); // undefined console.log("0" in a); // true console.log(a.hasOwnProperty(0)); // true
Deleting array elements in JavaScript - delete vs splice
Reviewed by Unknown
on
February 09, 2018
Rating:
No comments: