Javascript version of the in_array function (to determine if there is a specific value in the array)

  • 2020-03-30 02:56:24
  • OfStack

We often use this logic to determine whether a string or number is in an array, and many programming languages have specialized functions like PHP's in_array(). So does JS? Well, unfortunately, JS doesn't have a function like this, so we figured out whether the great JQ encapsulates this function, and we found the API, and JQ does encapsulate this function
JQuery. InArray (value, array) searches for the specified value in the array and returns its index (-1 if not found).
Value is the value to search for.
Array is an array through which to search.

Of course, in order to learn, I also wrote such a function:

function inArray1(needle,array,bool){  
    if(typeof needle=="string"||typeof needle=="number"){  
        for(var i in array){  
                    return i;  
                return true;  
        return false;  

Three arguments, find the needle in the array, bool is a Boolean, and if true returns the position of the needle in the array

Related articles: