javascript function inArray

前端 未结 5 1577
南方客
南方客 2020-11-28 13:52

I need a javascript function that can take in a string and an array, and return true if that string is in the array..

 function inArray(str, arr){
   ...
 }
         


        
相关标签:
5条回答
  • 2020-11-28 14:15

    Something like this?

    function in_array(needle, haystack)
    {
        for(var key in haystack)
        {
            if(needle === haystack[key])
            {
                return true;
            }
        }
    
        return false;
    }
    
    0 讨论(0)
  • 2020-11-28 14:21

    Take a look at this related question. Here's the code from the top-voted answer.

    function contains(a, obj) {
      var i = a.length;
      while (i--) {
        if (a[i] === obj) {
          return true;
        }
      }
      return false;
    }
    
    0 讨论(0)
  • 2020-11-28 14:25

    careful:

    indexOf() uses partial data. if you have '12', '1'

    indexOf('1') will get you the index of '12' not '1'

    0 讨论(0)
  • 2020-11-28 14:30

    you can use arr.indexOf()

    http://www.w3schools.com/jsref/jsref_indexof_array.asp

    0 讨论(0)
  • 2020-11-28 14:33

    You could just make an array prototype function ala:

    Array.prototype.hasValue = function(value) {
      var i;
      for (i=0; i<this.length; i++) { if (this[i] === value) return true; }
      return false;
    }
    
    if (['test'].hasValue('test')) alert('Yay!');
    

    Note the use of '===' instead of '==' you could change that if you need less specific matching... Otherwise [3].hasValue('3') will return false.

    0 讨论(0)
提交回复
热议问题