javascriptarrayselementextra

How can I prevent extra array elements being created in Javascript?


In PHP, if you do this

$var = array(); 
$var[5000] = 1;
echo count($var);

It prints 1.

In JS it makes the "missing" elements.

<script type="text/javascript">
    var fred = [];
    fred[10] = 1;
    alert(fred.length);
</script>

Alerts "11".

Can I prevent this? Is it good for anything? I'm a PHP coder trying to adapt to Javascript.

EDIT:

I'm working on an app that uses Google Maps v2 and markerManager. The code has been working for ages, but a problem has suddenly arisen in Chrome (17.0.963.56 m) where markers seem to be duplicated (or more) and then rendering moved markers goes completely wrong, often followed by a browser freeze-up. Looking in the DOM using Firebug, I found gazillions of "undefined" elements in arrays under the grid_ variable in markerManager. I figured that, if I could remove these, I might have slicker code, whether it fixes the marker problem or not. Thanks.


Solution

  • As a PHP coder, you're accustomed to array keys being fairly arbitrary. In JavaScript however, if you assign an array element numerically that doesn't exist, the array will be allocated with empty elements up to the one you created. That's the behavior you found. Objects, on the other hand, denoted by {} rather than [], accept arbitrary property names (with caution) and function a little more closely to how you're accustomed PHP's array structures functioning. This is not to say that JavaScript objects (or object literals) are a direct analogue to PHP arrays....

    If what you want is a data structure with a key called "10", that is a job for an object literal (though it isn't great practice to name object properties numerically.

    var fred = {};
    fred["10"] = 1;
    

    Note, the more normal syntax of dealing with an object literal is the object.property notation, but that is not valid for numeric properties:

    // name as a property
    fred.name = "fred";
    
    // Syntax error...
    fred.10 = 10;
    
    // Use [] notation for numeric properties:
    fred["10"] = 10;
    

    Object literals do not have a length property, however. So you cannot do:

    fred.length;
    // undefined