简体   繁体   English

如何访问数组中对象的变量

[英]How to access the variables of an object in an array

I have an array which I want to populate, every time a new startId and endID are chosen, however once I add the new object to the array, I cannot access the variables in the object, when I alert, I get undefined as a value. 每次选择新的startId和endID时,我都有一个要填充的数组,但是一旦将新对象添加到该数组中,便无法访问该对象中的变量,当我发出警报时,我将得到未定义的值。

This is my code; 这是我的代码;

        value = {start: this.startId, end :this.endId};

        this.array[this.array.length] = value;
        alert(this.array[this.array.length].start + " " + this.array[this.array.length].end)

I also tried this 我也尝试过

            value = {start: this.startId, end :this.endId};

            this.array[this.array.length] = value;
            alert(this.array[this.array.length][start] + " " + this.array[this.array.length][end])

This won't work since you are accessing a key that is outside of the array. 由于您访问的是阵列外部的键,因此无法使用。

Have a look at this example: 看一下这个例子:

[1,2,3]// an array with the indexes 0=1, 1=2 , 2=3
.length;//3

So while you can insert a new element at arrays.length position, you cannot get one from there, as it does not exist. 因此,尽管您可以在arrays.length位置插入一个新元素,但由于该元素不存在,因此无法从那里获取一个元素。

So you need to access the last element at the length-1 position: 因此,您需要在length-1位置访问最后一个元素:

alert(this.array[this.array.length-1].start);

Sidenote: 边注:

Instead of using array[array.length] to add a new element you can make use of the push function: 除了使用array [array.length]添加新元素,您还可以使用push函数:

this.array.push(value);

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

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