简体   繁体   中英

push value at index in array

I initialize my array as myArray=[]; I want to dynamically create an associative array in a for loop. I am trying to create a key index and push a new value in at the same time. I want each key index to be a number like '1': '2': '3': The number of indexes will be unknown so I need to create them in my loop I am not sure how to accomplish this or push more values into each index. My code is:

var myArray=[];
for(i=0; i<10; i++){
myArray['1'].push(i);
myArray['2'].push(i);
myArray['3'].push(i);
}
alert(myArray);

There is an error in the code . I apologize if this is similar to a repeat question. I can not find this answer in my searches though. Thanks for any help.

You must initialize the subarrays in order to push . Better start with the index 0 , tough.

var myArray = [[], [], []];
for(var i=0; i<10; i++){
    myArray[0].push(i);
    myArray[1].push(i);
    myArray[2].push(i);
}

JavaScript arrays should be used with numeric indexes. If you want a map from string-valued keys to values, use a simple object:

var myMap = {};

To populate the map, you'll have to initialize the arrays for each key:

var myMap = { '1': [], '2': [], '3': [] };

Then your loop will work as-is.

edit — I may have misinterpreted your question. If you want your outer array to use just numeric indexes (I saw the strings and generalized, perhaps inappropriately) then you can indeed use an array of arrays:

var myMap = [ null, [], [], [] ];

(The first null is for index 0, which is implicitly where JavaScript array indexes start.)

Several things are wrong here:

#1

You want myArray to be an associative array, so as an object, it would be defined like so:

myArray = {};

#2

You cannot push() data in an array that has not been declared. Declare those arrays first:

myArray['1'] = [];
myArray['2'] = [];
myArray['3'] = [];

#3

You cannot directly alert() an array or an object. You need to get a string representation of it:

alert( JSON.stringify(myArray,null,4) ); // null,4 provides easy to read formating

JS Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM