简体   繁体   中英

how to define array size inside objects in JavaScript?

Is there a way to define array size inside objects in Java Script? Like we do in C or C++, when we want user to enter values in array, we define a size and populate it using indexes according to user. Display is done using something like n[4] (assuming n is an array.)

   function activity(id, name, description, prior, post, start, end, current, status) {
         this.id = id;          //activity id
         this.name = name;          //activity name
          this.description = description;   //activity description  
         **this.prior = prior[];            // prior activities
         this.post = post[];            //post activities**
         this.start = start;            //activity start date
         this.end = end;            //activity end date
        this.currentWork = currentWork;     //current work that has been done
        this.status = status;       //current status
   }

I want prior and post to be arrays of size 3. I am making 18 instances of above object, each one with different value. Tell me how to access these values how to enter values in this array?

You can create an array of a specified size with:

this.prior = new Array(3);

However, Javascript arrays are not a fixed size -- if you assign beyond the end, it will automatically grow. So normally just just create an empty array:

this.prior = [];

and then assign elements or use this.prior.push(newElement) to add to it.

see this

array in javascript grows dynamically so according to that post you can just store the length in some variable and use it as for looping. like this

var data = [];
var arrlength = 10 ; // user-defined length

for(var i = 0; i < arrlength; i++) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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