In_array function Customization Method of PHP-like JS array _javascript tips

Source: Internet
Author: User
PHP's Array function In_array () is very convenient, but JS is not. In fact, I do not like the JS array ~

Stop it, go directly to the method
Copy Code code as follows:

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

Or
Copy Code code 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 possible. is actually a form, the writing is not the same.

Of course, there is another way I recommend it,
Copy Code code 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, do not understand what is the relationship, you just use my code to write good, quack.

Analog data detection is good
Copy Code code as follows:

var aa = new Array (1,2, ' AA ', ' BBB ', 4,5);
Alert (Aa.in_array (3));
Alert (Aa.in_array (' AA '));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.