user2394076
user2394076

Reputation:

Display object values

I have created an object person and created 2 properties for that person object in JavaScript. I passed data to that object as:

personA = new person("Michel","Newyork"); 
personB = new person("Roy","Miami"); 

What I need is, how to display both personA & personB values at same time through JavaScript?

Upvotes: 5

Views: 9921

Answers (3)

Mark
Mark

Reputation: 1093

You could also consider this approach:

var persons = {
    person: [],

    add: function(name, city)
    {
        this.person.push({
            'name': name,
            'city': city
        });
    }

};

persons.add("Michael", "New York");
persons.add("Roy", "Miami");

Output:

for(x in persons.person)
{
    console.log(x + ":");

    for(y in persons.person[x])
    {
        console.log(y + ": " + persons.person[x][y]);
    }
}

------

0:
name: Michael
city: New York
1:
name: Roy
city: Miami

Upvotes: 1

HBP
HBP

Reputation: 16053

If you simply want to display them on the console,for debug purposes, use

 console.log (personA, personB);

If you want to alert them to the screen :

 alert (JSON.stringify (personA), JSON.stringify (personB));

If you want to change a DOM element to contain the values :

 domElement.innerHTML = personA.name + ' from ' + personA.loc + ' and ' +
                        personB.name + ' from ' + personB.loc;

assuming here than name and loc are the property names you used.

Of course you can use any of these methods in any context depending on your requirements.

Upvotes: 2

SomeShinyObject
SomeShinyObject

Reputation: 7821

I'm going to assume person takes a name and loc (for location) since you didn't clarify:

var personArr = []; //create a person array
//Then push our people
personArr.push(personA);
personArr.push(personB);
for (var i = 0; i < personArr.length; i++) {
   console.log(personArr[i].name);
   console.log(personArr[i].loc);
}

If you're talking about literally at the same time, I won't say it's impossible, just not possible with JavaScript unless you use WebWorkers and those don't fair too well in IE.

Upvotes: 1

Related Questions