JavaScript simulation PHP function in

Source: Internet
Author: User
Tags php language

is to determine whether an element exists in the array of functions, since the JS string has indexof function, why not in the array object set a function like this, in fact, with indexof this idea is very good, do not know the development of JS Standard is based on what to consider, Such a common function is not taken into account.

JS to determine whether an element exists in a JS array, equivalent to the PHP language in the In_array function.

?

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

Usage is as follows:

?

1 2 var arr=new Array (["B", 2, "a", 4, "Test"]); Arr.in_array (' test ')//Determines whether the test string exists in the ARR array, returns true otherwise false, and returns true here

Note: This function is valid only for characters and numbers

There are similar functions in jquery: Http://docs.jquery.com/Utilities/jQuery.inArray

Its 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 the article to share all the content, I hope you can enjoy.

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: [email protected] 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.