Home > Web Front-end > JS Tutorial > body text

Collection of methods on how to determine whether elements in an array are repeated in javascript_javascript skills

WBOY
Release: 2016-05-16 19:19:19
Original
1134 people have browsed it

var str = new Array();  
比如有这么一组数组,里面放了20个18位的身份证号码  
要判断里面的身份证号码是否有重复  
如何快速判断?

复制代码 代码如下:

var ary = new Array("111","22","33","111");
    var s = ary.join(",")+",";
    for(var i=0;i {
if(s.replace(ary[i]+",","").indexOf(ary[i]+",")>-1)
 {
   alert("有重复!");
 }
}
 

复制代码 代码如下:

var ary = new Array("111","22","33","111");
var nary=ary.sort();
for(var i=0;i   {if (nary[i]==nary[i+1])
       {alert("重复内容:"+nary[i]);}
    }

活用正则表达式里的 \1 (第一个匹配结果)
先用 join() 把数组转换成字符串且夹塞指定的分隔符 \x0f(这种分隔符用户一般是输不进来的),这一步纯粹是为简化且精确脚本而做。
这种模式是我写 MzTreeView 的时候想出来的招数,可以跳过 for 循环达到极端的效率。
复制代码 代码如下:

var hash = {};
for(var i in arr) {
  if(hash[arr[i]])
    return true;
  hash[arr[i]] = true;
}
return false;


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template