简体   繁体   English

将值推入数组中的索引

[英]push value at index in array

I initialize my array as myArray=[]; 我将数组初始化为myArray = []; I want to dynamically create an associative array in a for loop. 我想在for循环中动态创建一个关联数组。 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. 我希望每个键索引都是一个类似'1':'2':'3'的数字:索引的数目将是未知的,因此我需要在循环中创建它们,但我不确定如何完成此操作或推入更多值进入每个索引。 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 . 您必须初始化子数组才能进行push Better start with the index 0 , tough. 最好从索引0开始,艰难。

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. JavaScript数组应与数字索引一起使用。 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.) (第一个null值用于索引0,这是JavaScript数组索引开始的隐式位置。)

Several things are wrong here: 这里有几处错误:

#1 #1

You want myArray to be an associative array, so as an object, it would be defined like so: 您希望myArray是一个关联数组,因此作为一个对象,它的定义如下:

myArray = {};

#2 #2

You cannot push() data in an array that has not been declared. 您不能在尚未声明的数组中push()数据。 Declare those arrays first: 首先声明这些数组:

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

#3 #3

You cannot directly alert() an array or an object. 您不能直接alert()数组或对象。 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 JS小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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