I am fairly new and don't really know how to word this question, so please bear with me. I would like to keep sets of data using arrays in javascript and access them sequentially using a counter. For example, I would like to display every piece of data about a person, one person at a time. Right now I am using something along the lines of this:
var firstNames = new Array("John", "Bob", "Anna", "Natalie");
var lastNames = new Array("Smith", "Price", "Johnson", "Baker");
var ages = newArray(34, 51, 12, 83);
And then accessing them with:
counter++;
firstNames[counter];
lastNames[counter];
ages[counter];
I would rather have each person's data in their own array. For example:
var person1 = new Array("John", "Smith", 34);
var person1 = new Array("Bob", "Price", 51);
var person1 = new Array("Anna", "Johnson", 83);
var person1 = new Array("Natalie", "Baker", 12);
How would I then access each piece of the array, one array at a time using a counter? Is there a better approach to this? I would appreciate any help or referral to information on this. Thanks!
What you need is an array of people objects:
var person1 = {firstName:"John", lastName:"Smith", age: 34};
var person2 = {firstName:"Bob", lastName:"Price", age: 51};
var person3 = {firstName:"Bob2", lastName:"Price2", age: 52};
var people = [person1, person2];
//you can also add to the list with push
people.push(person3);
var a = people[0].firstName; //John;
Here's a clean way of doing what you want to do for a list of arbitrary size:
function Person(fn, ln, a) {
this.firstName = fn;
this.lastName = ln;
this.age = a;
}
var firstNames = new Array("John", "Bob", "Anna", "Natalie");
var lastNames = new Array("Smith", "Price", "Johnson", "Baker");
var ages = new Array(34, 51, 12, 83);
var people = new Array();
for (var i = 0; i < firstNames.length; ++i) {
people.push(new Person(firstNames[i], lastNames[i], ages[i]));
}
people
now contains an array of Person
objects. You can access the first name of the second person by simply typing people[1].firstName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With