Write js extensions to determine whether an array contains an element

  • 2020-03-26 23:47:06
  • OfStack

The Contains method can be used in C# syntax to determine whether a collection Contains an element, but how do you handle this in javascript? Js does not contain the method.
We can use the js prototype extension to encapsulate a Contains method of our own.

Js code:
 
<script type="text/javascript"> 
$(function () { 
Array.prototype.contains = function (element) { //Using the prototype prototype of Array, I'm going to call a method I want to encapsulate called contains
for (var i = 0; i < this.length; i++) { 
if (this[i] == element) { //If an element in the array is the same as the element object you want to test, prove that the array contains that element, and return 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(","); //Assign a value to an array
$("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 the array object using the contains method does not have to be explicitly declared, that is, the italics in the code above can be shortened to:
 
var $subCategoryID = $("#hidSubCategory").val().split(","); 

Related articles: