2016-07-16 152 views
14

如何检查数组中的元素是否存在于underscore.js中?例如,我有['aaa', 'bbb', 'cfp', 'ddd'],并且想检查是否存在'cfp'。如果有,我想展示一些文字。我下面的代码不能正常工作,我不知道为什么:Underscore.js检查数组中的元素是否存在?

<% _.each(profile.designations, function(i) { %>                       
      <% if (typeOf profile.designations[i] == "cfp") { %>                       

      <div class="cfp-disclosure-text">                           

       <p>Show this text if does exist</p>                                  

      </div>                                  

      <% } %>                                  

      <% }); %> 
+1

取出TYPEOF –

+1

@torazaburo这不是我认为的PHP。 sk_225只是使用下划线作为模板引擎。 – marmeladze

回答

32

只需使用_.contains方法:

http://underscorejs.org/#contains

console.log(_.contains(['aaa', 'bbb', 'cfp', 'ddd'], 'cfp')); 
 
//=> true 
 

 
console.log(_.contains(['aaa', 'bbb', 'cfp', 'ddd'], 'bar')); 
 
//=> false
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>