简体   繁体   中英

How to iterate over this object

I have this object:

var navArray = {
  '#item1' : 0,
  '#item2' : 1,
  '#item3' : 2,
  '#item4' : 3,
  '#item5' : 4,
  '#item6' : 5
}

The ident var in the code below is a number and I need to find out which property it corresponds to in the array...so if ident is 1 I want to get #item2 back..

How do I do this?

var navArray = {
  '#item1' : 0,
  '#item2' : 1,
  '#item3' : 2,
  '#item4' : 3,
  '#item5' : 4,
  '#item6' : 5
}
if(typeof(ident) === "number") {
    for(i in navArray) {
    }
}

This should work:

var ident = 1,
    target = null;
for (var key in navArray) {
    if (navArray.hasOwnProperty(key)) { 
        if (navArray[key] === ident) {
            target = key;
            break;
        }
    }
}

alert (target); // "#item2"

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