JS Array Contains


indexOf() method: Search array and return the position of the found value, if not found, return -1, if more than 1 element were found, return the position of the first found value:

var arr = new Array(1,2,3,2,5);
var p = arr.indexOf(3) //p = 2
p = arr.indexOf(7) //p = -1
p = arr.indexOf(2) //p = 1
if (arr.indexOf(5)) alert("true")
else alert("flase");


lastIndexOf() method: Search array from the end, and return the position of the first found value, if not found, return -1:

var arr = new Array(1,2,3,2,5,11,14);
var p = arr.lastIndexOf(3) //p = 2
p = arr.lastIndexOf(7) //p = -1
p = arr.lastIndexOf(2) //p = 3


includes() method determines whether an array contains a value. Old version browsers may not support this method.

var a=["1","b","gg","ed"];
if ( a.includes("b") ) alert("exist");


in keyword can be used to determine whether an array contains a value:

var a=[1,2,3,4];
if ( 2 in a ) alert("exist");


in keyword can be used for checking whether a key exist in an associative array:

var zy = new Array();
zy["a3"]="aaa";zy["b3"]="bbb";zy["c3"]="ccc";
var str = "a3";
if (str in zy){
	alert(zy[str]);
}


Use prototype property to add "contains" method to the Array Object:

Array.prototype.contains = function(elem)
{
	for (var i in this)
	{
		if (this[i] == elem) return true;
	}
	return false;
}
var arr = [4,16,9];
if (arr.contains(4)) alert("yes");
else alert("no");

endmemo.com © 2024  | Terms of Use | Privacy | Home