Write the JS extension method to determine whether an array contains an element _javascript techniques

Source: Internet
Author: User
It is possible to use the Contains method to determine whether a collection contains an element in C # syntax, but similar questions are not contains in JavaScript.
We can use JS's prototype extension to encapsulate a contains method of our own.

JS Code:
Copy Code code as follows:

<script type= "Text/javascript" >
$ (function () {
Array.prototype.contains = function (Element) {//using the array's prototype prototype to point out a method name that I want to encapsulate contains
for (var i = 0; i < this.length; i++) {
if (this[i] = = Element) {//If an element in the array is equal to the element object you want to test, the proof array contains this element and returns True
return true;
}
}
}
Use an example to verify some of the methods we encapsulate
var $subCategoryID = $ ("#hidSubCategory"). Val ();
var $subCategoryIDs = new Array (); Construct an Array object
$subCategoryIDs = $subCategoryID. Split (","); assigning values to arrays
$ ("Input[type=radio]"). each (function () {
if ($subCategoryIDs. Contains (this). attr ("id")) {//Use the Contains method to determine if the array contains $ (this). attr ("id")
$ (this). attr ("Checked", true);
}
})
})
</script>

Verify that an array object using the Contains method does not have to be explicitly declared, that is, the italic portion of the preceding code can be abbreviated as:
Copy Code code as follows:

var $subCategoryID = $ ("#hidSubCategory"). Val (). Split (",");

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.