如何比较两个整数数组并按匹配规则返回对应提示消息数组
整数数组匹配提示功能代码修正说明
原代码存在的问题
- 变量名拼写错误:交替使用
Array1和array1,还出现未定义的hintArray、reference变量,不符合JS变量命名规范 - 逻辑冗余错误:判断值和位置是否匹配不需要嵌套循环,直接对比相同下标即可,嵌套循环会导致重复判断
- 数组对比错误:JS中数组是引用类型,直接用
===对比的是内存地址而非内容,无法判断数组元素是否完全相等 - return位置错误:每次push后直接return,会直接终止函数执行,无法收集所有匹配结果
- indexOf用法错误:
indexOf是数组方法不是属性,reference.indexOf[i]写法完全错误,取索引直接用循环的下标变量即可 - 规则顺序错误:完全匹配的判断应该放在最前面,否则先走循环收集了
Almost之后无法触发correct逻辑
修正后的实现代码
function check(array1, referenceArray) { let hint = []; // 优先判断是否完全匹配 const isFullyMatch = array1.every((val, index) => val === referenceArray[index]); if (isFullyMatch) { hint.push("correct"); return hint; } // 统计位置和值都匹配的数量,同时收集不匹配的元素用于后续值匹配判断 let exactCount = 0; const refUnmatched = []; const arrUnmatched = []; for (let i = 0; i < 3; i++) { if (array1[i] === referenceArray[i]) { exactCount++; } else { refUnmatched.push(referenceArray[i]); arrUnmatched.push(array1[i]); } } // 按数量添加Almost提示 for (let i = 0; i < exactCount; i++) { hint.push("Almost"); } // 统计仅值匹配、位置不匹配的数量 let valueCount = 0; const tempRef = [...refUnmatched]; for (const val of arrUnmatched) { const idx = tempRef.indexOf(val); if (idx !== -1) { valueCount++; tempRef.splice(idx, 1); // 移除已匹配的项避免重复计数 } } // 按数量添加not quite提示 for (let i = 0; i < valueCount; i++) { hint.push("not quite"); } // 无任何匹配的场景 if (hint.length === 0) { hint.push("incorrect"); } return hint; }
效果验证
使用你提供的示例测试:
const Array1 = [2,7,6]; const ReferenceArray = [2,9,7]; console.log(check(Array1, ReferenceArray)); // 输出 ["Almost", "not quite"]
其他场景测试结果:
- 完全匹配:
check([1,2,3], [1,2,3])返回["correct"] - 无任何匹配:
check([1,2,3], [4,5,6])返回["incorrect"] - 两个位置值都匹配:
check([1,2,4], [1,2,3])返回["Almost", "Almost"] - 两个值匹配位置都不对:
check([1,2,3], [2,1,4])返回["not quite", "not quite"]
内容的提问来源于stack exchange,提问作者QQQue
相关产品推荐
相关产品推荐

