0

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
4
  • 4
    Um... are you sure the problem is with the code you have posted? I don't see f.cardArray anywhere... Commented Aug 8, 2013 at 15:42
  • 1
    Ummm nowhere in your code do you use f.cardArray Commented Aug 8, 2013 at 15:42
  • In addition, as was mentioned in a now-deleted answer, you should start at a 0 index when iterating through arrays - array[2] in an array of length 2 will return an error. Commented Aug 8, 2013 at 15:43
  • I edited question, f.cardArray should be f.array. sza's answer is correct Commented Aug 8, 2013 at 16:00

1 Answer 1

4

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

Actually he has filled his array the same way he is reading it, so it should work shouldn't it ?
@Virus721: not for the last array element.
@collapsar Ho i just realized he used .push() instead [], but in that case it would have worked.
@Virus721: yes, it would have.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.