2011-05-09 73 views
0
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。我想检查这个每个元素。如何检查数组中是否有键:值或不?

+0

我什至不能在那里看到一个数组。请尝试发布一些**真实的**代码。 – 2011-05-09 10:23:51

+0

将代码更改为数组 – 2011-05-09 10:26:22

回答

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

还应该检查实际值:'if(people [i] .header ==='A')' – Rudie 2011-05-09 10:28:43

+0

@Rudie不确定这是否是实际要求。该OP是相当含糊的,但我认为他只想看看该参数是否存在* – 2011-05-09 10:29:21

+0

他在谈论'key:value',所以我想他也想知道/检查这个值。确实含糊不清。 – Rudie 2011-05-09 10:30:21

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',与:

1

您可以检查是否定义或不使用typeof

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