Javascript array member tests


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.