开发者

declare unnamed objects Javascript

开发者 https://www.devze.com 2023-03-01 06:54 出处:网络
I need to d开发者_如何学Goeclare a set of types of objects in javascript and then populate them. Being new, I can\'t seem to find a way.

I need to d开发者_如何学Goeclare a set of types of objects in javascript and then populate them. Being new, I can't seem to find a way.

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

I need to populate myarr with a set of ds objects dynamically populated. Can some one pls help?

Data format: ID,name,city,comments

This is what I am currently trying and failing:

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


It's worth stating that you don't need to create a class/constructor, you simply need a new object for each entry

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


You could create a simple object constructor:

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 ...
];

Please give the object a better name than Data though :)

As a simpler alternative, you could simply do this:

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


maybe something like this:

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


Try doing it like this, define your model object:

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

Then use it like this:

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

If you want validate the types, extend the definition like this:

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.');
  }
} 

In response to your edit, use it like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号