As others have said, you can use delete
. But JavaScript is an OO language, so everything is an object. Thus, I feel it necessary to point out a particular caveat.
In arrays, unlike plain old objects, using delete
leaves behind null
/ undefined
garbage, creating a "hole" in the array.
var array = [1,2,3,4];
delete array[2];
/* Expected result --> [1,2,4]
* Actual result --> [1,2,null,4]
*/
As you can see, delete
doesn't always work as one might expect. The value is deleted, but the memory is not reallocated.
Ignoring the problems inherent of null
in and of itself, this can be problematic if the array needs to be precise.
For example, say you are creating a webapp that uses JSON-serialization to store an array in a string (such as localStorage). Let's also say that the code uses the numerical indices of the array's members to "title" the values when drawing to the screen. Why are you doing this rather than just storing the "title" as well? To save memory, of course! Just in case you get that one user who runs a PDP-11 minicomputer from the 1960's, and wrote his own Elinks-based, JavaScript-compliant, line-printer-friendly browser because firefox takes too long to assemble...
Increasingly ridiculous edge-case scenario aside, using delete
on said array will result in null
polluting the data, cluttering the string, and probably causing bugs in the program later on. And if you check for null
, it would straight up skip the numbers.
if (array[index] == null)
continue;
else
title = (index + 1).toString();
/* 0 -> "1"
* 1 -> "2"
* 2 -> (nothing)
* 3 -> "4"
*/
Probably not what you wanted.
Now, you could keep a second iterator, like j
, to increment only when valid values are read from the array. But that wouldn't solve the clutter issue, and you still have to please that troll PDP-11 user. Alas, his computer doesn't have enough memory to hold two integers (don't ask how he got a JS interpreter running...). So he sends you an email in anger:
Hey, your webapp broke my browser! I checked my localStorage database after your stupid code made my browser segfault, and this is what I found:
>"tabs:['Hello World', 'foo bar baz', null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ... ]"
After clearing my precious data, it segfaulted again, and I did a backtrace, and what do I find? WHAT DO I FIND!? YOU USE TOO MANY VARIABLES!
>var i = index;
>var j = 1;
Grr, I am angry now.
-Troll Davidson
About now, you're at your wit's end. This guy has been complaining non-stop about your app, and you want to tell him to get a better computer.
Luckily, arrays do have a specialized method for deleting indices and reallocating memory: Array.prototype.splice()
. You could write something like this:
Array.prototype.remove = function(index){
this.splice(index,1);
}
...
array = [1,2,3,4];
array.remove(2);
// Result -> [1,2,4]
And just like that, you've pleased Mr. PDP-11. Hooray! (I'd still tell him off, though...)