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/
JavaScript doesn’t have string array keys like PHP & some other languages. What you have done is to add a property named
elem + ito thetmpArrayobject. It doesn’t affect the array’s.lengthproperty, even though the property is there and accessible, and it is not accessible via array methods like.pop(), .shift()Perhaps instead you should declare
tmpArrayas an object literal since you don’t appear to be using it with any numeric keys.