Custom method of in_array function similar to php's js array

高洛峰
Release: 2023-03-03 22:12:02
Original
1524 people have browsed it

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

Don’t say it, just use the method

Array.prototype.in_array = function(e) 
{ 
for(i=0;i<this.length;i++) 
{ 
if(this[i] == e) 
return true; 
} 
return false; 
}
Copy after login

or

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


both of which are fine. In fact, it’s just the same form, just written in different ways.

Of course, there is 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)); 
}
Copy after login

I personally like this better, it doesn’t matter if you don’t understand it, you can just use the code I wrote, quack. .

Just check the simulated data

var aa = new Array(1,2,&#39;aa&#39;,&#39;bbb&#39;,4,5); 
alert(aa.in_array(3)); 
alert(aa.in_array(&#39;aa&#39;));
Copy after login


For more related articles on the in_array function customization method of js arrays similar to php, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!