JS代码,使用Set如何判断数组是否重复
时间: 2023-12-10 20:37:18 浏览: 33
可以利用Set的特性,将数组转换成Set,再比较Set的长度和原数组的长度是否相等来判断数组是否重复。
示例代码如下:
```javascript
function isDuplicate(arr) {
return new Set(arr).size !== arr.length;
}
// 示例用法
const arr1 = [1, 2, 3];
console.log(isDuplicate(arr1)); // false
const arr2 = [1, 2, 3, 2];
console.log(isDuplicate(arr2)); // true
```
首先将数组转换成Set,Set会自动去重,然后比较Set的长度和原数组的长度是否相等,如果不相等,就说明数组有重复项,返回`true`。如果相等,就说明数组没有重复项,返回`false`。
相关问题
JS代码判断数组是否有重复值,并找出重复值
可以使用Set数据结构来判断数组是否有重复值,如果有,可以通过循环遍历数组,利用Object对象来找出重复的值。
代码如下:
```javascript
function findDuplicates(arr) {
let set = new Set();
let duplicates = [];
for (let i = 0; i < arr.length; i++) {
if (set.has(arr[i])) {
duplicates.push(arr[i]);
} else {
set.add(arr[i]);
}
}
return duplicates;
}
let arr = [1, 2, 3, 4, 5, 3, 6, 7, 8, 1];
let duplicates = findDuplicates(arr);
console.log(duplicates); // 输出 [3, 1]
```
这个函数会返回一个数组,包含了所有重复的元素。在这个例子中,重复的元素是3和1。
js 判断数组是否存在重复元素
可以通过以下代码来判断一个数组是否存在重复元素:
```javascript
function hasDuplicates(arr) {
return new Set(arr).size !== arr.length;
}
// 示例:
const arr1 = [1, 2, 3, 4, 5];
console.log(hasDuplicates(arr1)); // false
const arr2 = [1, 1, 2, 3, 4];
console.log(hasDuplicates(arr2)); // true
```
请注意:以上代码是使用 ES6 的 Set 数据结构实现的,因此需要在支持 Set 的环境下运行。如果需要支持不同的环境,可以考虑使用遍历数组的方式判断是否存在重复元素。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)