A custom method for the in_array function similar to PHP's js array

  • 2020-03-30 01:06:10
  • OfStack

PHP's array function in_array () is handy, but JS is not. I actually don't like JS arrays

Stop it and go straight to the method
 
Array.prototype.in_array = function(e) 
{ 
for(i=0;i<this.length;i++) 
{ 
if(this[i] == e) 
return true; 
} 
return false; 
} 

or
 
Array.prototype.in_array = function(e) 
{ 
for(i=0;i<this.length && this[i]!=e;i++); 
return !(i==this.length); 
} 

Both of these are fine. It's just a form, it's written differently.

Of course, there's another method that I recommend,
 
Array.prototype.S=String.fromCharCode(2); 
Array.prototype.in_array=function(e) 
{ 
var r=new RegExp(this.S+e+this.S); 
return (r.test(this.S+this.join(this.S)+this.S)); 
} 

Personally, I like this one, but if it doesn't matter, you can just use the code I wrote to make it quack quack.

Just check the analog data
 
var aa = new Array(1,2,'aa','bbb',4,5); 
alert(aa.in_array(3)); 
alert(aa.in_array('aa')); 

Related articles: