尝试制作对象(如一些评论中所建议的)我不确定增加的复杂性是否值得,但无论如何都会将它发布在这里以防万一它有用。在这种特殊情况下,一个对象几乎没有什么用途,可能更有Person
用的是一个聚合对象(PersonSet
(jsfiddle)
var names = ['John', 'Jim', 'Jack', 'Jill'],
ages = [25, 30, 31, 22],
genders = ['male', 'male', 'male', 'female'];
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
function PersonSet(names, ages, genders) {
this.content = [];
for (var i = 0; i < names.length; i++) {
this.content.push(new Person(names[i], ages[i], genders[i]));
// (alternatively...)
// this.content.push({name: names[i], age: ages[i], gender:
// genders[i]});
}
this.sort = function(aspect) {
this.content.sort(function(a, b) {
return ((a[aspect] < b[aspect]) ? -1 :
((a[aspect] > b[aspect]) ? 1 : 0));
});
};
this.get = function(aspect) {
var r = [];
for (var i = 0; i < this.content.length; i++) {
r.push(this.content[i][aspect]);
}
return r;
}
}
var personSet = new PersonSet(names, ages, genders);
personSet.sort('age');
console.log(personSet.get('name'), personSet.get('age'),
personSet.get('gender'));