Method for customizing the in_array function similar to the js array of php _ javascript tips-js tutorial

Source: Internet
Author: User
The PHP Array Function in_array () is very convenient. The following describes how to customize the in_array function similar to the js array of php. The specific implementation method is as follows, if you are interested, you can refer to the PHP Array Function in_array (), which is very convenient, but JS does not. Actually, I do not like JS arrays ~

Let's just move on.

The Code is as follows:


Array. prototype. in_array = function (e)
{
For (I = 0; I {
If (this [I] = e)
Return true;
}
Return false;
}


Or

The Code is as follows:


Array. prototype. in_array = function (e)
{
For (I = 0; I Return! (I = this. length );
}


Both of them are acceptable. It is actually a form, but the writing method is different.

Of course, there is another method I recommend,

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, but it doesn't matter if I don't understand it. You just need to use the code I wrote to get it ..

Just check the simulated data.

The Code is as follows:


Var aa = new Array (, 'A', 'bbb );
Alert (aa. in_array (3 ));
Alert (aa. in_array ('A '));

Related Article

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.