简体   繁体   English

如何在JavaScript中定义对象内部的数组大小?

[英]how to define array size inside objects in JavaScript?

Is there a way to define array size inside objects in Java Script? 有没有一种方法可以在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. 就像我们在C或C ++中所做的一样,当我们希望用户在数组中输入值时,我们定义一个大小并根据用户使用索引来填充它。 Display is done using something like n[4] (assuming n is an array.) 使用n [4]之类的东西来完成显示(假设n是一个数组)。

   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. 我想让post和post为大小为3的数组。我正在制作上述对象的18个实例,每个实例具有不同的值。 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. 但是,Javascript数组的大小不是固定的-如果您分配的末尾数量会自动增长。 So normally just just create an empty array: 因此,通常只需创建一个空数组即可:

this.prior = [];

and then assign elements or use this.prior.push(newElement) to add to it. 然后分配元素或使用this.prior.push(newElement)添加到其中。

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. javascript中的数组会动态增长,因此根据该帖子,您可以将长度存储在某个变量中,并将其用作循环。 like this 像这样

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

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

}

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

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