Underscore.js 检查数组中的元素是否存在?

Underscore.js to check if element in array exists?

如何检查数组中的元素是否存在于underscore.js中?例如,我有 ['aaa', 'bbb', 'cfp', 'ddd'],想检查 'cfp' 是否存在。如果是这样,我想显示一些文字。我下面的代码不起作用,我不确定为什么:

<% _.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>                                                                                                                                       

            <% } %>                                                                                                                                     

            <% }); %>

只需使用_.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>

你可以使用 ES6 数组 includes

const designations = ['aaa', 'bbb', 'cfp', 'ddd'];

const exists = fruits.includes('cfp');

console.log(exists);

或者我们可以直接使用

console.log(['aaa', 'bbb', 'cfp', 'ddd'].includes('cfp'))