3) 利用数组中的filter方法,将已知数组var arr = ['apple','banana','pear','apple','orange','orange']; 去重
时间: 2023-08-20 07:28:24 浏览: 42
可以使用 `filter()` 方法结合 `indexOf()` 方法来对数组进行去重。具体做法是,使用 `filter()` 方法遍历数组,只保留第一次出现的元素,其余的重复元素将被过滤掉。以下是代码实现:
```
var arr = ['apple', 'banana', 'pear', 'apple', 'orange', 'orange'];
var newArr = arr.filter(function(item, index, arr){
return arr.indexOf(item) === index;
});
console.log(newArr);
```
这段代码中,我们使用 `filter()` 方法遍历数组,对于每个元素,我们使用 `indexOf()` 方法查找它在数组中第一次出现的位置。如果当前元素在数组中第一次出现的位置就是当前索引 `index`,那么这个元素就是第一次出现的,我们就保留它。否则,这个元素就是重复的,我们就过滤掉它。最后,我们打印出去重后的数组 `newArr`。
相关问题
javascript封装方法 找出数组最大值var arr = [12, 34, 2, 5, 76];
好的,这是一个简单的JavaScript编程问题。可以使用循环或者Math.max()方法来找出数组中的最大值。下面是两种方法的代码示例:
1. 使用循环遍历数组并找到最大值:
```javascript
function findMax(arr) {
let max = arr[0]; // 假设第一个元素为最大值
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]; // 更新最大值
}
}
return max;
}
let arr = [12, 34, 2, 5, 76];
let max = findMax(arr);
console.log(max); // 输出 76
```
这段代码定义了一个名为`findMax`的方法,它接受一个数组作为参数,并使用for循环遍历数组中的每个元素,找到其中的最大值。
2. 使用Math.max()方法找到数组中的最大值:
```javascript
let arr = [12, 34, 2, 5, 76];
let max = Math.max(...arr);
console.log(max); // 输出 76
```
这段代码使用了ES6的扩展运算符`...`来将数组展开,然后使用Math.max()方法找到其中的最大值。
2)借助indexOf()方法判断此元素在该数组中首次出现的位置下标与循环的下标是否相等,将已知数组var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5,5,5]; 去重
好的,针对你的问题,我可以给出以下代码来去重:
```javascript
var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5,5,5];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (newArr.indexOf(arr[i]) === -1) {
newArr.push(arr[i]);
}
}
console.log(newArr); // [1, 23, 3, 5, 6, 7, 9, 8]
```
以上代码中,我们遍历原数组 `arr`,并且使用 `indexOf` 方法来判断当前元素是否已经存在于新数组 `newArr` 中。如果不存在的话,我们就将该元素添加到新数组中。最终,新数组 `newArr` 中的元素就是原数组 `arr` 中去重后的结果。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)