简体   繁体   中英

how to check in an array whether it has a key:value or not?

  var people =[{title:'Alan', hasChild:true},
        {title:'Alice', hasDetail:true},
        {title:'Amos', header'A'},
        {title:'Alonzo'},
        {title:'Brad'},
        {title:'Brent'},    
        {title:'Billy'},    
        {title:'Brenda'},   
        {title:'Callie'},
        {title:'Cassie'},   
        {title:'Chris'}];

I want to check in this array, whether it contains a key,value header:value in it or not. I want to check this for each elements.

This should do it:

for (var i = 0, c = people.length;i < c;i++) {
    if (people[i].header) {
        // yay
        // not sure wether you want to check the value as well
        // but if that is the case, you'd do this
        if (people[i].header == 'A') {
            // do some more stuff
        }
    } else {
        // nay
    }
}
for(var i = 0; i < array.length; ++i){
    if(array[i]["header"])
        //Do stuff with the header
    else
        //Do stuff without it
}

This should work... Though you've got an error in the element with the header - it should be header:'A' , with the :

you can check if it is defined or not using typeof

for (var i in arr) {    
    if (typeof arr[i].header !== 'undefined') {
       //key present
    }  else {
       //key not present
    }  
}

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