在Javascript中,如何检查数组是否具有重复值?

编程入门 行业动态 更新时间:2024-10-10 18:29:51
本文介绍了在Javascript中,如何检查数组是否具有重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 在javascript数组中查找重复值的最简单方法

如何检查数组是否有重复值?

How do I check if an array has duplicate values?

如果数组中的某些元素相同,则返回true。否则,返回false。

If some elements in the array are the same, then return true. Otherwise, return false.

['hello','goodbye','hey'] //return false because no duplicates exist ['hello','goodbye','hello'] // return true because duplicates exist

推荐答案

如果您有一个ES2015环境(截至撰写本文时:io.js,IE11,Chrome,Firefox,WebKit),那么以下内容将会起作用,并且会很快(即O(n)):

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) { return (new Set(array)).size !== array.length; }

如果你只需要字符串数组中的值,以下将起作用:

If you only need string values in the array, the following will work:

function hasDuplicates(array) { var valuesSoFar = Object.create(null); for (var i = 0; i < array.length; ++i) { var value = array[i]; if (value in valuesSoFar) { return true; } valuesSoFar[value] = true; } return false; }

我们使用哈希表 valuesSoFar 其键是我们到目前为止在数组中看到的值。我们使用中的进行查找,以查看是否已发现该值;如果是这样,我们将退出循环并返回 true 。

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.

如果你需要一个不仅仅是字符串值的函数,下面的方法就可以了,但效果不是很好;它是O(n 2 )而不是O(n)。

If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) { var valuesSoFar = []; for (var i = 0; i < array.length; ++i) { var value = array[i]; if (valuesSoFar.indexOf(value) !== -1) { return true; } valuesSoFar.push(value); } return false; }

区别在于我们使用数组代替哈希表 valuesSoFar ,因为JavaScript哈希表(即对象)只有字符串键。这意味着我们在中丢失了的O(1)查找时间,而是获得了的O(n)查询时间indexOf 。

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

更多推荐

在Javascript中,如何检查数组是否具有重复值?

本文发布于:2023-11-28 20:38:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643876.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!