4

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/

Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
asked Apr 26, 2012 at 3:00

1 Answer 1

8

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 ;
}
ThatBlairGuy
2,4601 gold badge19 silver badges36 bronze badges
answered Apr 26, 2012 at 3:02
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.