0

Hello all I am working in javascript and html5.I want to ask that how can we add an array as a data member of a class in javascript I have written a code

var bm =  new Bitmap(img); //It is a built in class of some library

/*Here what I want is to associate an array with object of bitmap*/
/* what i did is */
 var lpr = new Array();
 bm.lpr[0]= "xyz" ;
 bm.lpr[1]= "pqr" ;

but when I displayed the array.

alert(bm.lpr[0]);

I got the error

Uncaught TypeError: Cannot set property '0' of undefined

can any one please tell me the correct way of doing it.Also my array will be update at run time

Thanks

5
  • 1
    your bm variable has no lpr property, they are two different variables. I am not sure what are you trying to do... Commented Apr 5, 2012 at 12:31
  • Yes it has not but can add any property of data member to it Commented Apr 5, 2012 at 12:36
  • sure but you need to initialize that property in bm variable before you try to access its members... Commented Apr 5, 2012 at 12:38
  • Hmmm i am initilizing it.am I doing it wrong Commented Apr 5, 2012 at 12:40
  • 1
    yes you initialize lpr variable, but that doesnt make it bm's property. You should do bm.lpr = lpr before your alert... Commented Apr 5, 2012 at 12:42

2 Answers 2

2

If you want a property of the bm instance to hold an array, you can do that like so...

bm.lpr = ['xyz', 'pqr'];

Your alert() will then show what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

instead of bm.lpr assignments, do on lpr only and in the end update the bm object bm.lpr = lpr
bm.lpr has to be an Array before you can add items to that array; otherwise, you're trying to add items to undefined. If you don't want to initialize the values of the array at the beginning, you can write bm.lpr = [], and then you can push items into that array later on.
1

You only have to change one line:

 var bm =  new Bitmap(img);

 bm.lpr = new Array(); //this is the line you need to change
 bm.lpr[0]= "xyz" ;
 bm.lpr[1]= "pqr" ;


 alert(bm.lpr[0]);

Comments

Your Answer

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.