2

I want to iterate over an array of objects in order to get the oldest person and the youngest person. How could I get that? It looks like an easy task, but there is no way I can get the ages with simple for each loop. Any ideas?

var p = [
    { name : "Billy", age : 5 },
    { name : "Lucy", age : 31 },
    { name : "Jonny", age : 11 },
    { name : "Wolfgang", age : 78 },
    { name : "Robert", age : 23 }
];

I have seen this but it didn't help me in understanding the problem.

4

5 回答 5

6

Simple for loop

var high = 0,
    low;

//Start at 0 index, iterate until the array length, iterate by 1
for (var i = 0; i < p.length; i++) {
    //checking high
    if (p[i].age > high)
        high = p[i].age;

    //checking low
    if (p[i].age < low || low == null)
        low = p[i].age;
}
于 2013-10-07T12:21:08.390 回答
3

您可以使用 for in 循环来解决此问题。唯一需要记住的是循环只会给你索引。因此,您需要访问原始对象。

一个可能的解决方案是:

var maxPerson = p[0];

for(var i in p) {
    if (p[i].age > maxPerson.age)
        maxPerson = p[i];
}
于 2013-10-07T12:25:28.540 回答
2

要在 JavaScript 中迭代数组,请使用.forEach.

p.forEach(function(person){
    console.log(person.name + ' is ' + person.age + ' years old.');
});

请注意,.forEachIE 8 及更低版本不支持此功能。您可以使用es5-shim将该功能添加到旧浏览器,或者如果您已经使用 jQuery,则可以使用每个jQuery。

现在要获取最老和最年轻的,我们需要在遍历列表时存储最佳选择(jsFiddle):

var oldest = p[0];
var youngest = p[0];
p.forEach(function(person){
    if (oldest.age < person.age) { oldest = person; }
    if (person.age < youngest.age) { youngest = person; }
});

最后,oldestyoungest包含适当的对象。

于 2013-10-07T12:19:06.277 回答
1

If you want to retrieve only two objects, the oldest and the youngest, then the easiest way would be to sort the array in either ascending or descending order based on age, then take the first and last elements of the resulting array.

于 2013-10-07T12:21:04.367 回答
1

使用sort( mdn doc ) 将适用于每个浏览器:

p.sort(function (a, b) {
    return a.age - b.age;
});

var youngest = p[0];
var oldest = p[p.length - 1];

但是要小心,sort修改原始数组。您可以克隆它以绕过此问题:

var clone = [].concat(p).sort(/* compare function */);
var youngest = clone[0];
var oldest = clone[clone.length - 1];
于 2013-10-07T12:30:12.663 回答