欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript检查数据中是否存在相同的元素(两种方法)

程序员文章站 2023-11-08 09:44:34
这里是两个用于数组中查找重复元素的demo,可以看看啦

这里是两个用于数组中查找重复元素的demo,可以看看啦

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>title</title>
</head>
<body>
<input type="text" id="values" style="width: 100px;height: 25px;">
<button id="gain">获取</button>
<!--gain-->
</body>
<script src="jquery-2.2.2.min.js"></script>
<script type="text/javascript">
 //方法一
var arr1 = ["11", "22", "33", "44"];
 var arr=new array(arr1);
 array.prototype.in_array=function(e){
 var r=new regexp(','+e+',');
 return (r.test(','+this.join(this.s)+','));
 };
 $("#gain").on("click",function () {
 var newvalue=$("#values").val();
 console.log(newvalue);
 if(arr.in_array(newvalue)){
 alert("已重复,请不要重复添加");
 }else {
 arr1.push(newvalue);
 console.log(arr1);
 }
 })
 //方法二
function isarr(arr,value) {
 for(var i=0;i<arr.length;i++){
 if(value===arr[i]){
 return true;
 }
 }
 return false;
 }
 var arr2 = ["11", "22", "33", "44"];//用于进行比较的数组
$("#gain").on("click",function () {
 var value2=$("#values").val();
 if(isarr(arr2,value2)){
 alert("已重复,请不要重复添加")
 }else {
 arr2.push(value2);
 console.log(arr2);
 }
 })
</script>
</html>

总结

以上所述是小编给大家介绍的javascript检查数据中是否存在相同的元素(两种方法),希望对大家有所帮助