Reputation: 8066
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
Upvotes: 0
Views: 66
Reputation: 54514
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.
Upvotes: 4