初学者Javascript阵列和计数器

时间:2015-05-07 20:55:57

标签: javascript arrays

我很新,并不知道如何说出这个问题,所以请耐心等待。我想在javascript中使用数组保存数据集,并使用计数器顺序访问它们。例如,我想一次显示一个人,一个人的每一条数据。现在我正在使用以下内容:

var firstNames = new Array("John", "Bob", "Anna", "Natalie");
var lastNames = new Array("Smith", "Price", "Johnson", "Baker");
var ages = newArray(34, 51, 12, 83);

然后使用以下方式访问它们:

counter++;
firstNames[counter];
lastNames[counter];
ages[counter];

我宁愿让每个人的数据都在他们自己的数组中。例如:

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);

然后我如何使用计数器一次访问数组的每个部分?有更好的方法吗?我将不胜感激任何帮助或转介此信息。谢谢!

2 个答案:

答案 0 :(得分:6)

您需要的是一系列人物对象:

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;

答案 1 :(得分:1)

这是一种干净的方式,可以为任意大小的列表执行您想要做的事情:

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现在包含一组Person个对象。只需输入people[1].firstName

即可访问第二人的名字