不使用new相关,使用js,对list元素去重
时间: 2024-03-16 07:41:37 浏览: 24
我们可以使用Set集合实现对list元素的去重,具体实现如下:
```javascript
let list = [1, 2, 3, 3, 4, 4, 5];
let uniqueList = [...new Set(list)];
console.log(uniqueList); // [1, 2, 3, 4, 5]
```
这里我们首先定义了一个包含重复元素的list数组,然后使用Set集合对其进行去重,并将结果存储在uniqueList数组中。最后,我们可以通过console.log输出uniqueList数组,验证去重是否成功。
需要注意的是,由于Set集合是ES6中新增的数据结构,因此在使用之前需要确保你的代码运行环境支持该特性。如果你的代码运行环境不支持Set集合,你可以通过其他方式实现去重,比如使用for循环遍历数组,或者使用reduce方法等。
相关问题
js list 去重
以下是两种JavaScript去重的方法:
1. 使用Set数据结构
```javascript
var list = [1, 2, 1, {name: 1}, {name: 1}, 'Shaoyouqing', 'Shaoyouqing', null, null, NaN, 0, 0, {}, '', '', [1, 2], [1, 2], undefined, false, false, true, NaN, true, NaN, 9, undefined, 'true', 'false', 'true'];
var uniqueList = Array.from(new Set(list));
console.log(uniqueList);
```
2. 使用双重循环和splice方法
```javascript
var list = [1, 2, 1, {name: 1}, {name: 1}, 'Shaoyouqing', 'Shaoyouqing', null, null, NaN, 0, 0, {}, '', '', [1, 2], [1, 2], undefined, false, false, true, NaN, true, NaN, 9, undefined, 'true', 'false', 'true'];
for (var i = 0; i < list.length; i++) {
for (var j = i + 1; j < list.length; j++) {
if (list[i] === list[j]) {
list.splice(j, 1);
j--;
}
}
}
console.log(list);
```
js list对象去重
你可以使用 Set 数据结构来实现 JavaScript 数组去重,也可以使用 Array.filter() 方法结合 indexOf() 方法来实现去重。以下是两种方法的示例代码:
使用 Set 数据结构:
```
let arr = [1, 2, 2, 3, 3, 4, 5, 5];
let uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
```
使用 Array.filter() 方法结合 indexOf() 方法:
```
let arr = [1, 2, 2, 3, 3, 4, 5, 5];
let uniqueArr = arr.filter((item, index, arr) => {
return arr.indexOf(item) === index;
});
console.log(uniqueArr); // [1, 2, 3, 4, 5]
```
在以上代码中,我们都得到了一个去重后的数组 uniqueArr。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)