[英]Javascript storing multiple fields in an array
I was wondering if it's possible to store multiple different fields in a dynamic array using Javascript. 我想知道是否有可能使用Javascript在动态数组中存储多个不同的字段。
In Informix it is called a dynamic array of records and it is accomplished like this 在Informix中,它称为记录的动态数组,并且可以像这样完成
# define array of record
la_data dynamic array of record
var_idno integer,
var_desc char(30)
end record
# populate array of record
for lv_cnt = 1 to 10
let la_data[lv_cnt].var_idno = lv_cnt
let la_data[lv_cnt].var_desc = "dummy data"
end for
# use stored data
display la_data[5].var_idno # will output 5
display la_data[5].var_desc # will output dummy data
How would I do something similar (or completely different) using Javascript 我如何使用Javascript做类似(或完全不同)的事情
// define array of record
var la_data = [];
// populate array of record
for (var lv_cnt = 1; lv_cnt <= 10; lv_cnt++) {
// This initializes an object we can put your properties on
la_data[lv_cnt] = {};
la_data[lv_cnt]['var_idno'] = lv_cnt;
la_data[lv_cnt]['var_desc'] = "dummy data";
}
// use stored data
console.log(la_data[5].var_idno) // will output 5
console.log(la_data[5].var_desc) // will output dummy data
Fiddle: http://jsfiddle.net/xxqkfuot/ 小提琴: http : //jsfiddle.net/xxqkfuot/
As you can see in other answers there are simpler ways to do this but I was attempting to keep the code as similar as possible so you could see the connection between the lines. 如您在其他答案中所见,有更简单的方法可以执行此操作,但是我试图使代码尽可能相似,以便您可以看到行之间的连接。
I suppose you could create sometihng like a dynamic array in javascript, but the simplest and most idiomatic thing to do with pure javascript would be to use a list: 我想您可以像在javascript中创建动态数组一样创建某种样式,但是使用纯javascript要做的最简单也是最惯用的方法是使用列表:
var list = [];
for (i = 0; i < 10; i++)
list.push({var_idno: i, var_desc: 'Dummy data'});
JavaScript is loosely typed so this is actually too
easy to do. JavaScript是松散类型的,因此实际上
too
容易做到。
var one = 1;//int
var two = "String";//String
var three = {
"name": "Foo",
"address": "bar"
};//Object
var array = [one, two, three];
console.log(array[0]);//1
console.log(array[1]);//String
console.log(array[1]);//[Object]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.