How to find if an array contains a specific string in JavaScript/jQuery?

This question already has an answer here:

  • How do I check if an array includes an object in JavaScript? 40 answers

  • You really don't need jQuery for this.

    var myarr = ["I", "like", "turtles"];
    var arraycontainsturtles = (myarr.indexOf("turtles") > -1);
    

    or

    function arrayContains(needle, arrhaystack)
    {
        return (arrhaystack.indexOf(needle) > -1);
    }
    

    It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.


    jQuery offers $.inArray :

    Note that inArray returns the index of the element found, so 0 indicates the element is the first in the array. -1 indicates the element was not found.

    var categoriesPresent = ['word', 'word', 'specialword', 'word'];
    var categoriesNotPresent = ['word', 'word', 'word'];
    
    var foundPresent = $.inArray('specialword', categoriesPresent) > -1;
    var foundNotPresent = $.inArray('specialword', categoriesNotPresent) > -1;
    
    console.log(foundPresent, foundNotPresent); // true false
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Here you go:

    $.inArray('specialword', arr)
    

    This function returns a positive integer (the array index of the given value), or -1 if the given value was not found in the array.

    Live demo: http://jsfiddle.net/simevidas/5Gdfc/

    You probably want to use this like so:

    if ( $.inArray('specialword', arr) > -1 ) {
        // the value is in the array
    }
    
    链接地址: http://www.djcxy.com/p/13012.html

    上一篇: 未定义的变量,值== false!值

    下一篇: 如何查找数组是否包含JavaScript / jQuery中的特定字符串?