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://

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.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.