检测如果JavaScript数组中存在重复的条目最快的方法? [英] fastest way to detect if duplicate entry exists in javascript array?

查看:105
本文介绍了检测如果JavaScript数组中存在重复的条目最快的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var arr = ['test0','test2','test0'];

像上面的,有与价值TEST0两个相同的条目,如何最有效地检查吗?

Like the above,there are two identical entries with value "test0",how to check it most efficiently?

推荐答案

如果您排序的阵列,重复的是彼此相邻,使他们很容易地发现:

If you sort the array, the duplicates are next to each other so that they are easy to find:

arr.sort();
var last = arr[0];
for (var i=1; i<arr.length; i++) {
   if (arr[i] == last) alert('Duplicate : '+last);
   last = arr[i];
}

这篇关于检测如果JavaScript数组中存在重复的条目最快的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆