js查找数组中相同元素的下标
时间: 2023-08-12 07:30:44 浏览: 181
可以使用 JavaScript 的 indexOf 和 lastIndexOf 方法来查找数组中相同元素的下标。具体方法如下:
1. 首先遍历数组中的每个元素,利用 indexOf 方法查找该元素在数组中第一次出现的位置。
2. 如果该元素在数组中出现了多次,那么利用 lastIndexOf 方法查找该元素在数组中最后一次出现的位置。
3. 将找到的位置存入一个新的数组中,最后返回该数组即可。
下面是一个示例代码:
```javascript
function findSameIndex(arr) {
var indexArr = [];
for (var i = 0; i < arr.length; i++) {
var firstIndex = arr.indexOf(arr[i]); // 查找第一次出现的位置
var lastIndex = arr.lastIndexOf(arr[i]); // 查找最后一次出现的位置
if (firstIndex !== lastIndex && indexArr.indexOf(firstIndex) === -1) { // 判断是否是重复元素并且未添加到结果数组中
indexArr.push(firstIndex);
}
}
return indexArr;
}
// 示例
var arr = [1, 2, 3, 4, 5, 2, 6, 7, 3];
console.log(findSameIndex(arr)); // [1, 6, 8]
```
上述代码中,findSameIndex 函数接收一个数组参数 arr,返回一个包含相同元素下标的数组 indexArr。该函数首先利用 indexOf 方法查找数组中每个元素第一次出现的位置,然后利用 lastIndexOf 方法查找该元素最后一次出现的位置。最后判断该元素是否是重复元素并且未添加到结果数组中,如果是则将第一次出现的位置添加到结果数组中。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)