2013-05-02 44 views
3
 var employee = 
     { 
      Column1: null, 
      Column2: null, 

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

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

       return obj; 
      } 
     }; 

在C#创建对象的名单,我会做这样的事情:如何在JavaScript

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。

+4

你听说过数组? https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Predefined_Core_Objects#Array_Object,http://eloquentjavascript.net/chapter4.html。应该在每个JavaScript教程中进行介绍。 – 2013-05-02 18:19:48

+0

http://stackoverflow.com/questions/5868850/creating-list-of-objects-in-javascript – Nullify 2013-05-02 18:26:24

回答

6

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

var employees = []; 

for (var i = 0; i < 10; i++) { 
    employees.push({ 
     Column1: 'column 1 of emp' + i, 
     Column2: 'column 1 of emp' + i 
    }); 
} 
+0

它的效果很好。 – gangt 2013-05-02 18:31:58

3
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

+0

这是问题的以前版本的答案吗? – Bergi 2013-05-02 18:35:28

1

这是一个老问题,但只是想作出贡献。我用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'/>