Home >Web Front-end >JS Tutorial >Custom method of in_array function similar to php's js array_javascript skills

Custom method of in_array function similar to php's js array_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:06:331011browse

PHP's array function in_array() is very convenient, but JS is not. In fact, I don’t like JS arrays~

Stop talking, go directly to the method

Copy the code The code is as follows :

Array.prototype.in_array = function(e)
{
for(i=0;i{
if( this[i] == e)
return true;
}
return false;
}

or
Copy code The code is as follows:

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

Both of these are acceptable . In fact, it’s just the same form, just written in different ways.

Of course, there is another method that I recommend,
Copy the code The code is as follows:

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));
}

I personally like this better, see It doesn't matter if you don't understand, just use the code I wrote, quack. .

Just check the simulated data
Copy the code The code is as follows:

var aa = new Array(1,2,'aa','bbb',4,5);
alert(aa.in_array(3));
alert(aa.in_array('aa')) ;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn