字符串去重方法,通过 Set 数据结构来进行,直接上案例:
const imgSrc = "/weaver/weaver.file.FileDownload?fileid=a0857727b1bf1288a0a7ccb0a92350beae4f9bedb2f79aa7399fd08c1be1f05ea3180aceb261e08d29cb3dad8eaf1bcad4d3d3f222d4c6e08,/weaver/weaver.file.FileDownload?fileid=a50bec7fc01072c69d298f27f4303556e1775ffe0cbaec7816a8001b7994519de7b62fcb6f4b27ede19de31a7fe1f7cb26e8662b6d7f37c27";
const imgId = "22380,22381";
// 使用split方法把它们转化为数组
let picSrc = imgSrc.split(",");
let picId = imgId.split(",");
const set = new Set();
const uniqueList = [];
for (let i = 0; i < picSrc.length; i++) {
const item = picSrc[i];
const id = picId[i];
// 通过组合 picSrc 和 picId 形成字符串作为判断依据,如果已存在则跳过,否则添加到结果数组中
const key = item + id;
if (!set.has(key)) {
set.add(key);
uniqueList.push({
id: 2,
picSrc: item,
picId: id
});
}
}
使用了一个 Set 数据结构来记录已存在的元素,通过将 picSrc 和 picId 组合成一个唯一的字符串作为判断依据。如果在遍历过程中发现已经存在该字符串,则跳过该元素;否则将其添加到结果数组 uniqueList 中。最终得到的 uniqueList 即为去重后的数组。