gogoWebsite

js determine whether an element exists in the array (four methods)

Updated to 6 hours ago

Method 1: Using indexOf

Returns -1 for nonexistence and the index of the first occurrence for existence.

      // js checks to see if an array contains an element.
      // method 1 indexOf
      var arr = [100,20,50,58,6,69,36,45,78,66,45]
      if((66)==-1){
            ("Does not exist.")
      }else{
            ("Exists, index is:",(66))
      }

Method 2: Utilizing find

Its argument is a callback function that is traversed by all the array elements in turn until the first element with a true return value is found, and then that element is returned, otherwise it is undefined.

      var arr = [100,20,50,58,6,69,36,45,78,66,45]
      (function(value,index,arr){
            if(value==45){
                  ("exists",index)
            }
      })
      (param)

To find 45, find finds all existing 45s and their indexes.

Method 3: Utilizing some

The some method is also used to detect whether there is an element that satisfies the condition, if so, it does not continue to retrieve the following elements and returns true, if none of them do, it returns a false.

Usage is similar to find, except that find returns the element that satisfies the condition, while some returns a Boolean value.In terms of semantics, it's more relevant whether the inclusion returns a boolean value

      let arr = [100,20,50,58,6,69,36,45,78,66,45]
      // some
      let result = (ele => ele === 45) //true
      if (result) {
      //do something...
      };
      (result)

Act IV: includes

ES6 new array method, used to detect whether the array contains an element, if it contains return true, otherwise return false, more powerful is, can directly detect NaN:

vantageNeedless to say, the simplest way to do it is none, no callbacks, no complicated writing, one method directly.

drawbacksIt's the low version browser support that's not very friendly

      let arr = [100,20,50,58,6,69,36,45,78,66,45,NaN]
      // Method 4
      let flag = (1100)
      let flag1 = (NaN)

      (flag,flag1)

Recommended to use includes() method, convenient and one step~