繁体   English   中英

如何在javascript中创建对象列表

[英]how to create list of objects in javascript

        var employee =
        {
            Column1: null,
            Column2: null,

            create: function () {
                var obj = new Object();

                obj.Column1 = "";
                obj.Column2 = "";

                return obj;
            }
        };

在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);
}

我需要在javascript中做同样的事情。

非常直接的方法来创建一个对象数组。

var employees = [];

for (var i = 0; i < 10; i++) {
    employees.push({
        Column1: 'column 1 of emp' + i,
        Column2: 'column 1 of emp' + i
    });
}
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 }
];

用于访问列表使用:

list[index].date

这是一个古老的问题,但只是想为此做出贡献。 我用了数组

 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'/> 

暂无
暂无

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

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