简体   繁体   中英

Using for-in loop to find an object

I am working on some Javascript object exersice. I am stuck on using for in loop to find which model is the worst (highest number) and print the model. Here is what I have so far but it print all the model out which not correct.

var object = {"Camry":1,"Honda":2,"Ford":3,"Hyundai":10};
var count = "";
for (var prop in object) {
  if (object[prop] > count) { 
    count = object[prop];
  }
  console.log(prop);
}

The expected output is "Hyundai"

Thank you for your help!

You are printing the value of prop in the loop, so for all properties the value will be printed.

You need to have another variable outside the loop which will store the value of the latest prop with max count

var object = {
    "Camry": 1,
    "Honda": 2,
    "Ford": 3,
    "Hyundai": 10
};
var count = 0,
    type;
for (var prop in object) {
    if (object[prop] > count) {
        count = object[prop];
        type = prop;
    }
}
console.log(type);

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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