如何检查一个数组是否有一个键:值或不?

时间:2011-05-09 10:21:21

标签: javascript

  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。我想对每个元素进行检查。

3 个答案:

答案 0 :(得分:1)

应该这样做:

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

答案 1 :(得分:1)

for(var i = 0; i < array.length; ++i){
    if(array[i]["header"])
        //Do stuff with the header
    else
        //Do stuff without it
}

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

答案 2 :(得分:1)

您可以使用typeof

检查是否已定义
for (var i in arr) {    
    if (typeof arr[i].header !== 'undefined') {
       //key present
    }  else {
       //key not present
    }  
}