How to search for a value in an Array of JavaScript?

This question already has an answer here:

  • Best way to find if an item is in a JavaScript array? [duplicate] 8 answers
  • Check if object is array? 38 answers

  • You can use the indexOf() function you simply do this : array.indexOf("string") It will return -1 if the item is not found, otherwise just the position. Here's a link W3Schools.


    I think that has been asked thousands of times:

    if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){
       alert("You did something wrong!");
    }
    

    Watch out as old versions of IE don't know indexOf . (but who needs IE?)


    Use indexOf

    function search(arr,obj) {
        return (arr.indexOf(obj) != -1);
    }
    

    Test cases:

    search(["a","b"], "a"); // true
    search(["a","b"], "c"); //false
    
    链接地址: http://www.djcxy.com/p/27576.html

    上一篇: 更精致的Javascript类型?

    下一篇: 如何搜索JavaScript数组中的值?