Index of rows in js array

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

I do 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 tmpArray, it is empty and the size is 0, when I remove "elem" from the index of the array, it works correctly, what should I do? here's a real example http://jsfiddle.net/dfg3x/

+3
source share
1 answer

There are no string array keys in JavaScript, such as PHP and some other languages. What you did was add a property with a name elem + ito the object tmpArray. This does not affect the property of the array .length, although the property exists and is available, and it is not available using array methods such as.pop(), .shift()

, tmpArray , - .

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 ;
}
+8

All Articles