如何在数组中检查它是否有键:值

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

本文关键字:是否 检查 数组      更新时间:2023-09-26
  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'}];

我想检查这个数组,它是否包含键,值header:value。我想为每个元素检查这一点。

这应该可以做到:

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
}

这应该有效...虽然你在带有标题的元素中有一个错误 - 它应该是header:'A'的,带有:

您可以使用typeof来检查它是否已定义

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