基于ES6的JavaScript需求:检测重复编号对应不同城市并报错
如何检测同一编号对应不同城市的冲突(ES6实现)
没问题,咱们来搞定这个需求——要检查给定的编号数组和城市数组里,有没有同一个编号对应不同城市的情况对吧?用ES6的特性可以很优雅地实现,我给你两种常用的方案:
方案一:遍历检查(遇到第一个冲突就提示)
这个方案会在遍历过程中一旦发现冲突就立即输出错误,适合只需要知道是否存在冲突或者找到第一个冲突的场景:
const number = ['123', '123', '987', '567','675','675']; const city = ['Mumbai', 'Pune', 'Delhi', 'Bangalore','london','New York']; // 先确保两个数组长度一致,避免遍历出错 if (number.length !== city.length) { console.error("错误:编号数组与城市数组长度不匹配,请检查数据!"); } else { const cityMap = new Map(); let hasConflict = false; for (let i = 0; i < number.length; i++) { const currentNum = number[i]; const currentCity = city[i]; if (cityMap.has(currentNum)) { const storedCity = cityMap.get(currentNum); // 对比当前城市与已存储的城市 if (storedCity !== currentCity) { console.error(`❌ 冲突:编号 ${currentNum} 同时对应城市 "${storedCity}" 和 "${currentCity}"`); hasConflict = true; // 如果只需要第一个冲突,可以在这里加 break; 终止遍历 } } else { // 编号首次出现,存入映射表 cityMap.set(currentNum, currentCity); } } if (!hasConflict) { console.log("✅ 所有编号对应的城市均无冲突"); } }
方案二:收集所有冲突(函数式风格)
如果需要找出所有冲突的编号,用reduce来实现会更方便,它能把所有冲突都收集到一个数组里:
const number = ['123', '123', '987', '567','675','675']; const city = ['Mumbai', 'Pune', 'Delhi', 'Bangalore','london','New York']; // 先校验数组长度 if (number.length !== city.length) { console.error("错误:编号数组与城市数组长度不匹配,请检查数据!"); } else { const result = number.reduce((acc, num, index) => { const currentCity = city[index]; if (acc.map.has(num)) { const storedCity = acc.map.get(num); if (storedCity !== currentCity) { // 把冲突信息存入数组 acc.conflicts.push(`编号 ${num} 对应冲突城市:"${storedCity}" 和 "${currentCity}"`); } } else { acc.map.set(num, currentCity); } return acc; }, { map: new Map(), conflicts: [] }); if (result.conflicts.length > 0) { console.error("⚠️ 检测到以下冲突:"); result.conflicts.forEach(conflict => console.error(conflict)); } else { console.log("✅ 无冲突"); } }
额外注意点
- 大小写敏感:上面的代码会区分城市名称的大小写(比如
london和London会被认为是不同城市),如果需要忽略大小写,可以在存储和对比时把城市转成统一大小写,比如currentCity.toLowerCase()。 - 数据完整性:一定要先校验两个数组的长度是否一致,不然会出现遍历到一半数组越界的问题。
内容的提问来源于stack exchange,提问作者Alok Agase
相关产品推荐
相关产品推荐

