Skip to main content
9 of 13
added 26 characters in body
bortunac
  • 4.8k
  • 1
  • 36
  • 24

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,'has', { value:function(o,flag){ if(flag === undefined){ return this.indexOf(o) !== -1; } else{ // only for raw js object for(var v in this){ if(JSON.stringify(this[v]) === JSON.stringify(o)) return true; } return false; }, // writable:false, // enumerable:false } ) 

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

//use like [22 ,'a', {prop:'x'}].has(12) // false ["a","b"].has("a") // true [1,{a:1}].has({a:1},1) // true [1,{a:1}].has({a:1}) // false 

the use of 2nd arg (flag) forces a compare by value instead of reference

bortunac
  • 4.8k
  • 1
  • 36
  • 24