Skip to content

String index in a JavaScript array

I want to use a specific string in addition to a number to the index of array,

I make like this

var array = new Array();
$(document).ready(function(){
    array = addToArray();
    console.log("array size " + array.length);
});

function addToArray(){
    var i = 0;
    var tmpArray = new Array();
    while(i<10){
        if(i>9){
            addToArray();
            i++;
        }
        else{
            tmpArray["elem"+i] = "i";
            console.log(tmpArray["elem"+i]); // It prints out!!!
            i++;
        }
    }
    console.debug(tmpArray);

    return tmpArray;
}

‚Äč When I print out the tmpArray, it’s empty. Also the size is 0. When I remove the “elem” from the index of the array, it works properly. What should I do?

Here’s a real example: http://jsfiddle.net/dfg3x/

Answer

JavaScript doesn’t have string array keys like PHP & some other languages. What you have done is to add a property named elem + i to the tmpArray object. It doesn’t affect the array’s .length property, even though the property is there and accessible, and it is not accessible via array methods like .pop(), .shift()

Perhaps instead you should declare tmpArray as an object literal since you don’t appear to be using it with any numeric keys.

function addToArray() {
    var i = 0;
    // Make an object literal
    var tmpObj = {};
    while(i<10) {
       if(i>9) {
          addToArray();
          i++;
       }
       else {
          tmpObj["elem"+i] = "i";
          console.log(tmpObj["elem"+i]); //it prints out !!!
          i++;
       }
    }
    console.debug(tmpObj );

    return tmpObj ;
}