用Javascript将数组["a","b","a",1,"d","b",1,"c",2,"e","d"] 重复的元素 后面 加上 编号
时间: 2023-08-16 07:06:53 浏览: 62
JavaScript 实现二维数组去重复的数
回答:要用Javascript将数组["a","b","a",1,"d","b",1,"c",2,"e","d"]中重复的元素后面加上编号,可以使用以下代码实现:
```javascript
function addIndexToDuplicates(arr) {
var count = {};
var newArr = [];
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (count[item === undefined) {
count[item = 1;
} else {
count[item]++;
item += count[item];
}
newArr.push(item);
}
return newArr;
}
var demo = addIndexToDuplicates(["a","b","a",1,"d","b",1,"c",2,"e","d"]);
console.log(demo);
```
这段代码会遍历数组中的每个元素,使用一个计数器对象`count`来记录每个元素出现的次数。如果一个元素在计数器对象中不存在,则将其计数设为1。如果一个元素在计数器对象中已经存在,则将其计数加1,并在元素后面添加该计数。最后,将处理后的元素依次添加到新数组`newArr`中,并将新数组返回。运行这段代码,你将得到["a","b","a1",1,"d","b1",2,"c",2,"e","d2"]作为结果。<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* *2* *3* [JavaScript数组去重](https://blog.csdn.net/qq_44728587/article/details/119972515)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
阅读全文