const numbers = [1, 2, 3, 4, 5,2]; reduce去重
时间: 2023-10-13 13:04:26 浏览: 26
使用 `reduce` 方法也可以对数组进行去重操作,以下是示例代码:
```
const numbers = [1, 2, 3, 4, 5, 2];
const uniqueNumbers = numbers.reduce((acc, curr) => {
if (!acc.includes(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
```
上述代码中,`reduce` 方法的第一个参数是一个回调函数,该函数接收两个参数,第一个参数 `acc` 是累加器,第二个参数 `curr` 是当前遍历到的数组元素。回调函数中,我们通过判断 `acc` 数组是否包含 `curr` 元素来决定是否将 `curr` 元素加入到 `acc` 数组中。最终返回 `acc` 数组即可。
相关问题
const numbers = [1, 2, 3, 4, 5,2]; 去重
可以使用 Set 数据结构来去重,也可以使用 Array.filter() 方法。以下是两种方法的示例代码:
使用 Set 数据结构:
```
const numbers = [1, 2, 3, 4, 5, 2];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
```
使用 Array.filter() 方法:
```
const numbers = [1, 2, 3, 4, 5, 2];
const uniqueNumbers = numbers.filter((number, index) => {
return numbers.indexOf(number) === index;
});
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
```
const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = numbers.map((num) => num * num); console.log(squaredNumbers); // [1, 4, 9, 16, 25]
你的代码是正确的,它使用了 `map` 函数对数组 `numbers` 中的每个元素进行平方操作,并返回一个新的数组 `squaredNumbers`。最后,通过 `console.log` 打印出了结果 `[1, 4, 9, 16, 25]`。
这里的箭头函数 `(num) => num * num` 是传递给 `map` 函数的回调函数,它接受一个参数 `num`,并返回 `num` 的平方值。在 `map` 函数内部,它会遍历数组 `numbers` 中的每个元素,并将回调函数的返回值作为新数组的对应元素。
因此,最终得到的 `squaredNumbers` 数组就是每个元素的平方值组成的新数组。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)