javascript 如何在javascript中创建对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16344994/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:16:13 来源:igfitidea点击:
how to create list of objects in javascript
提问by GaneshT
var employee =
{
Column1: null,
Column2: null,
create: function () {
var obj = new Object();
obj.Column1 = "";
obj.Column2 = "";
return obj;
}
};
In C# I would do something like this:
在 C# 中,我会做这样的事情:
List<Employee> employees = new List<Employee>();
for (int i = 0; i < 10; i++)
{
Employee emp = new Employee()
{
Column1 = "column 1 of emp" + i;
Column2 = "column 2 of emp" + i;
}
employees.Add(emp);
}
I need to do the same in javascript.
我需要在 javascript 中做同样的事情。
回答by Feisty Mango
Pretty straight forward approach to creating an array of objects.
创建对象数组的非常直接的方法。
var employees = [];
for (var i = 0; i < 10; i++) {
employees.push({
Column1: 'column 1 of emp' + i,
Column2: 'column 1 of emp' + i
});
}
回答by Mr ASquare
It's a Old question but just wanna contribute to it. I used Arrays
这是一个老问题,但只是想对此做出贡献。我使用了数组
function car(brand, color, year, price) {
this.brand = brand;
this.color = color;
this.year = year;
this.price = price;
}
var my = new Array();
my.push(new car("Ford", "Black", 2017, 15000));
my.push(new car("Hyundai", "Red", 2017, 17000));
document.getElementById('ford').value = my[0].price;
document.getElementById('hyundai').value = my[1].price;
Ford price: <input type="text" id='ford'/><br><br>
Hyndai price: <input type="text" id='hyundai'/>
回答by Nullify
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
for accessing the list use :
访问列表使用:
list[index].date
list[index].date