Arrays, delete v. splice

Delete doesn’t really delete an array item like you think it does. It replaces whatever was there with undefined.

Consider:

(function () {
  "use strict";
  var myArray = ["one", "two", "three", "four"];
  delete myArray[2];

  window.onload = function () {
    var message, htmlMarkup, i;
    message = document.getElementById('LabelMessage');
    htmlMarkup = "<p>myArray Length: " + myArray.length + "</p>";
    for (i = 0; i < myArray.length; i = i + 1) {
      htmlMarkup += "<p>myArray[" + i + "]: " + myArray[i] + "</p>";
    }
    message.innerHTML = htmlMarkup;
  };
}());

With the following HTML:


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Document</title>
<script src="Test.js" type="text/javascript"></script>
</head>

<body>
<h1>My JavaScript Tests</h1>
<div id="LabelMessage">Test</div>
</body>
</html>

What we see is an array length of 4 (not 3), and undefined instead of “three”.

To truly remove the third item in the array, and shift the fourth one up or left to fill-in for the third one, use:

myArray.splice(2, 1);

No comments yet

Leave a comment