Posted By

scarfboy on 07/17/08


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

liuran


Javascript array member tests


 / Published in: JavaScript
 

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.

  1. function in_test(ary,stricttype) {
  2. for (var i=0; i<ary.length; i++) {
  3. if (ary[i]==this)
  4. if (stricttype) return typeof(ary[i])==typeof(this)
  5. else return true;
  6. }
  7. return false;
  8. }
  9. String.prototype.in = in_test;
  10. Number.prototype.in = in_test;
  11. //you could add it on Boolean, Date, but would you use it?
  12.  
  13. Array.prototype.contains = function(o,stricttype) {
  14. for (var i=0; i<this.length; i++) {
  15. if (this[i]==o)
  16. if (stricttype) return typeof(this[i])==typeof(o)
  17. else return true;
  18. if (this[i]==o) return true;
  19. }
  20. return false;
  21. }

Report this snippet  

You need to login to post a comment.