Javascript simulates the php function in_array, javascriptin_array

Source: Internet
Author: User

Javascript simulates the php function in_array, javascriptin_array

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

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:

Var arr = new Array (["B", 2, "a", 4, "test"]); arr. in_array ('test'); // determines 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:

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.