数组let a=[1,2,3,4,4,5,6]去重必须使用indexOf方法去重
时间: 2023-03-26 16:00:21 浏览: 70
可以使用indexOf方法去重,但是还有其他更简便的方法,比如使用Set数据结构或者使用ES6的新特性Set去重。例如:let a=[1,2,3,4,4,5,6]; let b=[...new Set(a)]; console.log(b); // [1, 2, 3, 4, 5, 6]
相关问题
借助indexOf()方法判断此元素在该数组中首次出现的位置下标与循环的下标是否相等,将已知数组var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5,5,5]; 去重
好的,那我来具体讲解一下这种方法的实现步骤:
1. 定义一个新数组result用于存放去重后的元素;
2. 遍历原数组arr,如果该元素在原数组中的下标等于循环的下标i,则将该元素添加到result中;
3. 遍历完整个数组后,返回去重后的数组result。
代码实现如下:
```
function unique(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) === i) {
result.push(arr[i]);
}
}
return result;
}
let arr = [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5, 5, 5];
let result = unique(arr);
console.log(result); // [1, 23, 3, 5, 6, 7, 9, 8]
```
需要注意的是,这种方法的时间复杂度也比较高,为O(n^2),不适合处理大规模的数组。此外,使用indexOf()方法还有一个问题就是它无法去重NaN和{}等复杂数据类型。
借助新数组 通过indexOf方判断当前元素在数组中的索引如果与循环的下标相等则添加到新数组中,将已知数组var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5,5,5]; 去重
好的,那我来具体讲解一下这种方法的实现步骤:
1. 定义一个新数组result用于存放去重后的元素;
2. 遍历原数组arr,判断该元素在原数组中第一次出现的下标是否等于循环的下标i,如果相等则将该元素添加到result中;
3. 遍历完整个数组后,返回去重后的数组result。
代码实现如下:
```
function unique(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) === i) {
result.push(arr[i]);
}
}
return result;
}
let arr = [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5, 5, 5];
let result = unique(arr);
console.log(result); // [1, 23, 3, 5, 6, 7, 9, 8]
```
需要注意的是,这种方法的时间复杂度也比较高,为O(n^2),不适合处理大规模的数组。此外,使用indexOf()方法还有一个问题就是它无法去重NaN和{}等复杂数据类型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)