Return to Snippet

Revision: 7286
at July 17, 2008 06:34 by scarfboy


Initial Code
function in_test(ary,stricttype) {
  for (var i=0; i<ary.length; i++) {
    if (ary[i]==this) 
      if (stricttype) return typeof(ary[i])==typeof(this)
      else return true;
  }
  return false;
}
String.prototype.in = in_test;
Number.prototype.in = in_test;
//you could add it on Boolean, Date, but would you use it?
 
Array.prototype.contains = function(o,stricttype) {
  for (var i=0; i<this.length; i++) {
      if (this[i]==o)
        if (stricttype) return typeof(this[i])==typeof(o)
        else return true;
    if (this[i]==o) return true;
  }
  return false;
}

Initial URL

                                

Initial Description
Given:
`a=['1',2,6];`

Allows things like:  
`
  a.contains(2); //true  
  '1'.in(a);  
  (1).in(a,true); //type not identical, so false  
  (1).in(a);      //no type check, so true  
`  
  
I never actually used this, it was more of an exercise in playing with JS.

Initial Title
Javascript  array member tests

Initial Tags

                                

Initial Language
JavaScript