jquery 判断元素是否存在于数组中

时间:2023-03-09 08:38:04
jquery  判断元素是否存在于数组中

要判断数组中是否包含某个元素,从原理来来说,就是遍历整个数组,然后判断是否相等

可以使用Jquery提供的方法:

$.inArray("元素(字符串)",数组名称) 进行判断 ,当存在该元素(字符串)时,返回该元素在数组的下标,不存在时返回 -1

 $(function () {
var array = ["asp.net", "asp.net mvc", "html5", "css3", "jquery", "JavaScript"];
var index = $.inArray("asp.net mvc", array); //结果:index=1
if (index >= 0) {
console.log("数组array包含asp.net mvc下标为:" + index);
} else {
console.log("数组array 不包含asp.net mvc下标为:" + index);
}
});