Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - array[id].method not working?

I have a for loop running that goes through each item in my array and executes the array item with a method. For some reason this returns as undefined, though without the .method it works fine. Here's my code:

    var people = ["susan", "david", "bob", "verity", "rhys", "charles"]
    
        function characters(name, sex) {
            this.name = name;
            this.sex = sex;
        }
    
    var susan = new characters("Susan", "Female");
    var david = new characters("David","Male");
    var bob = new characters("Bob","Male");
    var verity = new characters("Verity","Female");
    var rhys = new characters("Rhys","Male");
    var charles = new characters("Charles","Male");
    
    characters.prototype.info = function() {
        alert("Hi my name is " + this.name + " and I am a " + this.sex);
    }
    
    
    for(i = 0; i < people.length;i++) {
        people[i].info();
    }

Expected behaviour is that an alert that says "Hi my name is [name] and I am a [sex]" for each character but instead nothing happens.

like image 631
Sebastian Olsen Avatar asked Jan 20 '26 15:01

Sebastian Olsen


2 Answers

Your problem is that your array is an array of strings and not an array of characters objects, which is what your loop is expecting.

people[i] for each iteration of the loop is not the object you've created, but rather a string containing the variable name of each object. Because of this, calling your info() method will be unsuccessful since you're calling it on a string rather than a characters object.

Remove the quotes and rearrange your code so that your array declaration comes after your variable declarations, and it will work fine:

function characters(name, sex) {
  this.name = name;
  this.sex = sex;
}

characters.prototype.info = function() {
  alert("Hi my name is " + this.name + " and I am a " + this.sex);
}

var susan = new characters("Susan", "Female");
var david = new characters("David", "Male");
var bob = new characters("Bob", "Male");
var verity = new characters("Verity", "Female");
var rhys = new characters("Rhys", "Male");
var charles = new characters("Charles", "Male");

var people = [susan, david, bob, verity, rhys, charles];

for (i = 0; i < people.length; i++) {
  people[i].info();
}
like image 134
AstroCB Avatar answered Jan 23 '26 05:01

AstroCB


people is an array of strings not objects.

Move this line:

var people = ["susan", "david", "bob", "verity", "rhys", "charles"]

so it is after the lines where you declare and assign values to the variables.

Then remove the quotes so you have variables instead of string literals.

var people = [susan, david, bob, verity, rhys, charles];
like image 27
Quentin Avatar answered Jan 23 '26 05:01

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!