Best way to find if an item is in a JavaScript array? -


this question has answer here:

what best way find if object in array?

this best way know:

function include(arr, obj) {     for(var i=0; i<arr.length; i++) {         if (arr[i] == obj) return true;     } }  include([1,2,3,4], 3); // true include([1,2,3,4], 6); // undefined 

function include(arr,obj) {     return (arr.indexof(obj) != -1); } 

edit: not work on ie6, 7 or 8 though. best workaround define if it's not present:

  1. mozilla's (ecma-262) version:

      if (!array.prototype.indexof)   {         array.prototype.indexof = function(searchelement /*, fromindex */)      {       "use strict";      if (this === void 0 || === null)       throw new typeerror();      var t = object(this);     var len = t.length >>> 0;     if (len === 0)       return -1;      var n = 0;     if (arguments.length > 0)     {       n = number(arguments[1]);       if (n !== n)         n = 0;       else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))         n = (n > 0 || -1) * math.floor(math.abs(n));     }      if (n >= len)       return -1;      var k = n >= 0           ? n           : math.max(len - math.abs(n), 0);      (; k < len; k++)     {       if (k in t && t[k] === searchelement)         return k;     }     return -1;   };  } 
  2. daniel james's version:

    if (!array.prototype.indexof) {   array.prototype.indexof = function (obj, fromindex) {     if (fromindex == null) {         fromindex = 0;     } else if (fromindex < 0) {         fromindex = math.max(0, this.length + fromindex);     }     (var = fromindex, j = this.length; < j; i++) {         if (this[i] === obj)             return i;     }     return -1;   }; } 
  3. roosteronacid's version:

    array.prototype.hasobject = (   !array.indexof ? function (o)   {     var l = this.length + 1;     while (l -= 1)     {         if (this[l - 1] === o)         {             return true;         }     }     return false;   } : function (o)   {     return (this.indexof(o) !== -1);   } ); 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -