0

I've the following object structure (just a sample object):

var Sample = function Sample (name)
{ this.init(name); };

Sample.prototype.init = function (name)
{ this.name_ = name; }

Sample.prototype.getName = function ()
{ return 'The name is '+this.name_; }

var obj = new Sample();
console.log ( obj.getName() );

When I do something like above it works well and print inside console as it has to be. But when I have a array collection I can't access the getName() function. For exemple:

var biblio = [];

biblio.push(new Sample('A'));
biblio.push(new Sample('B'));
biblio.push(new Sample('C'));
biblio.push(new Sample('D'));

for ( var i = 0; i < biblio.lenght; i++ )
{ console.log ( biblio[i].getName() ); }

For the case above, I always get undefined. But outside of the for usign something like biblio[0].getName() it works well.

How can I access the function of a object in a for loop?

1
  • typo in lenght Commented Jun 6, 2018 at 19:44

1 Answer 1

3

Just correct this biblio.length and It will work according to you!.

var Sample = function Sample (name)
{ this.init(name); };

Sample.prototype.init = function (name)
{ this.name_ = name; }

Sample.prototype.getName = function ()
{ return 'The name is '+this.name_; }

var obj = new Sample();
console.log ( obj.getName() );

var biblio = [];

biblio.push(new Sample('A'));
biblio.push(new Sample('B'));
biblio.push(new Sample('C'));
biblio.push(new Sample('D'));

for ( var i = 0; i < biblio.length; i++ )
{ console.log ( biblio[i].getName() ); }

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

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.