Javascript 将元素添加到多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8630765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add element to multidimensional array
提问by Mustapha George
if I define a multi-dimentional javascript array like this
如果我像这样定义一个多维javascript数组
//var myStack = new Array(3);
// *** edit ***
var myStack = {};
What is the best way to insert one value at a time?
一次插入一个值的最佳方法是什么?
myStack[1][1][0] = myValue;
I want to read a database and write one value at a time. Example:
我想读取一个数据库并一次写入一个值。例子:
myStack[recordNo][1]['FirstName'] = myValue;
回答by Rob W
Inserting a single value can be done through one line of code:
插入单个值可以通过一行代码完成:
myStack[1] = [,[value]];
Or, the long-winded way:
或者,冗长的方式:
myStack[1] = [];
myStack[1][1] = [];
myStack[1][1][0] = value;
Either method will populate the array myStack
with multiple arrays, and finally set the desired value, as requested at the question.
任何一种方法都将myStack
使用多个数组填充数组,最后按照问题的要求设置所需的值。
EDIT: As a response to the updated question, the following can be used:
编辑:作为对更新问题的回应,可以使用以下内容:
myStack[recordNo] = [,{'FirstName': myValue}];
回答by Frederik.L
To avoid dealing with an array index for every dimensions (which could lead to mistakes if you don't pay attention for a second), you can use a push
approach. It makes it easier to read / debug, especially when you have a great number of dimensions :
为了避免处理每个维度的数组索引(如果您一秒钟不注意,可能会导致错误),您可以使用一种push
方法。它使阅读/调试更容易,尤其是当您有大量维度时:
// some constants for navigation purpose
var FIELD_FNAME=0;
var FIELD_LNAME=1;
var FIELD_JOB=2;
// initialize your stack
var myStack=[];
// create a new row
var row = [];
var fname = "Peter";
row.push(fname);
var lname = "Johnson";
row.push(lname);
var job = "Game Director";
row.push(job);
// insert the row
myStack.push(row);
Then it would be possible to iterate like this :
那么就可以像这样迭代:
for (var i=0;i<myStack.length;i++) {
var row = myStack[i];
var fname = row[FIELD_FNAME];
var lname = row[FIELD_LNAME];
var job = row[FIELD_JOB];
}
回答by user2889474
for example:
例如:
var varname={};
for (var k = 0; k < result.rows.length; k++) {
varname[k] =
{
'id': result.rows.item(k).id,
'name': result.rows.item(k).name
};
}
回答by kevinji
You can use three for
loops, if you are inserting all of the values into the array at one time:
for
如果一次将所有值插入数组,则可以使用三个循环:
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 3; k++) {
myStack[i][j][k] = myValue;
}
}
}