声明未命名的对象Javascript

时间:2011-04-27 18:33:38

标签: javascript arrays

我需要在javascript中声明一组对象类型,然后填充它们。作为新人,我似乎找不到办法。

var ds {INT,STRING,STRING,STRING};
var myarr = []

我需要使用动态填充的一组ds对象来填充myarr。有人可以帮忙吗?

数据格式: ID,名称,城市,注释

这就是我目前正在尝试和失败的原因:

var data=[];
var ds = {  ID:0, Name:"", City:"",Comments:""};

for ( var i = 0; i < input.length; ++i ) {
        ds.ID = input[i].ID;
        ds.Name = input[i].Name;
        ds.City = input[i].City;
        ds.Comments = input[i].Comments;
        data.push(ds);
}

4 个答案:

答案 0 :(得分:0)

尝试这样做,定义你的模型对象:

DataModel = function(id, name, city, comments) {
  this.id = id;
  this.name = name;
  this.city = city;
  this.comments = comments;
} 

然后像这样使用它:

var myarr = [new DataModel(1, 'foo', 'Toronto', 'This is a comment'),
             new DataModel(2, 'bar', 'Vancouver', 'This is a comment again!')];

如果要验证类型,请按以下方式扩展定义:

DataModel = function(id, name, city, comments) {
  if (id instanceof Number && name instanceof String && city instanceof String && comments instanceof String) {
    this.id = id;
    this.name = name;
    this.city = city;
    this.comments = comments;
  } else {
    throw new Error('DataModel parameters did not validate.');
  }
} 

为了响应您的编辑,请使用它:

for (var i = 0; i < input.length; ++i ) {
     var d = new DataModel(input[i].ID, input[i].Name, input[i].City, input[i].Comments;
     data.push(d);
}

答案 1 :(得分:0)

您可以创建一个简单的对象构造函数:

var Data = function(id, name, city, comments) {
    this.id = id;
    this.name = name;
    this.city = city;
    this.comments = comments;
};

var myarr = [
    new Data(1, 'foo', 'bar', 'baz'),
    ... etc ...
];

请给对象一个比数据更好的名称,但是:)

作为一种更简单的替代方案,您可以简单地执行此操作:

var myarr = [
    { id: 1, name: 'foo', city: 'bar', comments: 'baz' },
    { id: 2, name: 'foo', city: 'bar', comments: 'baz' },
    ... etc ...
];

答案 2 :(得分:0)

可能是这样的:

var myarr = []
var ds = { ID:1,name:"boston",city:"boston",comments:"warm today"};
for(var i = 0; i < 5; i++){
  myarr.push(ds);
}

答案 3 :(得分:0)

值得说明你不需要 来创建一个类/构造函数,你只需要为每个条目创建一个新对象

for ( var i = 0; i < input.length; ++i ) {
        var ds = new Object(); // var ds = {} is equivalent
        ds.ID = input[i].ID;
        ds.Name = input[i].Name;
        ds.City = input[i].City;
        ds.Comments = input[i].Comments;
        data.push(ds);
}