简体   繁体   English

迭代一组对象

[英]Iterating over an array of objects

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. 我已经看到了这个,但它没有帮助我理解这个问题。

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

You can use a for in loop to solve this. 您可以使用for循环来解决此问题。 The only thing you need to remember that the loop will give you only the index. 你唯一需要记住的是循环只给你索引。 Therefore you need to access the original object. 因此,您需要访问原始对象。

A possible solution is: 可能的解决方案是:

var maxPerson = p[0];

for(var i in p) {
    if (p[i].age > maxPerson.age)
        maxPerson = p[i];
}

To iterate over array in JavaScript, you use .forEach . 要在JavaScript中迭代数组,请使用.forEach

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

Note that .forEach is not supported in IE 8 and below. 请注意,IE 8及更低版本不支持.forEach You can use es5-shim to add that functionality to old browsers, or use jQuery each if you already use jQuery anyway. 您可以使用ES5,垫片到功能添加到旧的浏览器,或使用jQuery的每一个 ,如果你已经使用jQuery反正。

Now to get the oldest and the youngest we need to store the best choices as we loop over the list ( jsFiddle ): 现在,为了获得最老和最年轻的我们需要存储最佳选择,因为我们循环遍历列表( 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; }
});

In the end, oldest and youngest will contain the appropriate objects. 最后, oldestyoungest将包含适当的对象。

如果您只想检索最旧和最年轻的两个对象,那么最简单的方法是根据年龄按升序或降序对数组进行排序 ,然后获取结果数组的第一个和最后一个元素。

Using sort ( mdn doc ) will work in every browser : 使用sortmdn doc )可以在每个浏览器中使用:

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

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

Be careful however, sort modifies the original array. 但是要小心, sort会修改原始数组。 You may clone it in order to bypass this issue : 您可以克隆它以绕过此问题:

var clone = [].concat(p).sort(/* compare function */);
var youngest = clone[0];
var oldest = clone[clone.length - 1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM