Javascript simulation php function in_array

Source: Internet
Author: User

Javascript simulation php function in_array

It is to determine whether an element exists in an Array function. Since string in js has an indexOf function, why not set such a function in an Array object, in fact, the idea of using indexOf is quite good. I don't know what to consider for setting JS standards. I didn't take such a common function into consideration.

Js determines whether an element exists in a js array, which is equivalent to the in_array function in php.

?

1

2

3

4

5

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

};

The usage is as follows:

?

1

2

Var arr = new Array (["B", 2, "a", 4, "test"]);

Arr. in_array ('test'); // checks whether the test string exists in the arr array. If yes, true is returned. Otherwise, false is returned. true is returned here.

Note: This function is only valid for characters and numbers.

JQuery has a similar function: http://docs.jquery.com/Utilities/jQuery.inArray

The Code is as follows:

?

1

2

3

4

5

6

7

Function inArray (needle, haystack ){

Var length = haystack. length;

For (var I = 0; I <length; I ++ ){

If (haystack [I] = needle) return true;

}

Return false;

}

The above is all the content shared in this article. I hope you will like it.

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.