Below are my javascript code:
function A (no ){
this.no=no;
};
function AController (){
this.amount =0;
this.array=[];
};
AController.prototype.initArray=function(){
for(var i=1;i<=this.amount;i++){
var tem=new A(i) ;
this.array.push(tem);
}
};
then I execute somewhere
var f=new AController();
f.amount=2;
f.initArray();
for(var i=1 ;i<=2;i++){
f.array[i].no=0;
}
but it always reports
JS: TypeError: f.array[i] is undefined
your comment welcome
asked Aug 8, 2013 at 15:40
1 Answer 1
You need to loop from 0
for (var i = 0; i < 2; i++) {
f.array[i].no = 0;
}
After push
operations, the array is [A(1), A(2)]
, so f.array[2]
will be undefined
. Since you tried to assign no
property on the 3rd object in the array
which is undefined
, hence you got that error.
answered Aug 8, 2013 at 15:43
Sign up to request clarification or add additional context in comments.
4 Comments
Virus721
Actually he has filled his array the same way he is reading it, so it should work shouldn't it ?
collapsar
@Virus721: not for the last array element.
Virus721
@collapsar Ho i just realized he used .push() instead [], but in that case it would have worked.
collapsar
@Virus721: yes, it would have.
lang-js
f.cardArray
anywhere...f.cardArray
0
index when iterating through arrays -array[2]
in an array of length 2 will return an error.