Sunday, February 12, 2012

My associative array doesnt store objects


It seems it's always empty :




var idStruttura=2;
var arrayMarkers=new Array();

arrayMarkers["sede_"+idStruttura] = "ciao";
alert(arrayMarkers.length);



Prints always 0. Why? And how can I fix it?

5 comments:

  1. An array is not an associative array, however the array object is an object, and all objects are associative arrays. If you use a string as key when assigning items to the array, you are not using it as an array, you are using it as an object.

    The length property of the array returns how many items you have stored in the array. If you also use the array object as an associative array, that won't affect how you use the array as an array.

    ReplyDelete
  2. There is no length when you store objects, only when you use the array as intended.

    Try this (DEMO)

    var idStruttura=2;
    var arrayMarkers={}; // creates a more appropriate object than []

    arrayMarkers["sede_"+idStruttura] = "ciao";
    arrayMarkers["sede_"+(++idStruttura)] = "espresso";
    var len = 0;
    for (var o in arrayMarkers) {
    if (arrayMarkers.hasOwnProperty(o)) len++;
    }
    arrayMarkers.length=len
    alert(arrayMarkers.length)

    ReplyDelete
  3. What you've created is a regular array object and added a property to it called sede_.... JavaScript doesn't use associative arrays in the same way a language like PHP does. Arrays are objects that can have properties, but those properties are not among the numerically indexed array elements.

    var idStruttura=2;
    var arrayMarkers=new Array();

    // Push an object onto the array having one property:
    arrayMarkers.push({"sede_" + idStruttura : "ciao"});

    // Or declare it as an object to begin with:
    // This makes more sense....
    var objMarkers = {};
    objMarkers['sede_' + id] = 'ciao';

    ReplyDelete
  4. array's in javascript (unlike php) cannot have string key's, only numeric keys. If you want a string literal as a key, please use objects

    ReplyDelete
  5. What you need is a simple Object, not an Array. Arrays have numeric indexes.

    var markers = {};
    markers['sede_' + id] = 'ciao';


    Also note that {} is the same as new Object() and [] is the same as new Array(). Always use the former ones. It's much clear to any JS developer.

    ReplyDelete