Node.js技术问询:如何实现词汇顺序不符时控制台输出false?
解决按指定数组序列校验词汇顺序的问题
看起来你需要严格校验消息中的词汇是否遵循一组数组的先后顺序——也就是前一个数组里的所有词汇必须全部出现在后一个数组的词汇之前,后续添加的数组也要遵循这个递进规则。我来给你一个清晰的实现思路和代码示例:
核心逻辑
我们需要:
- 把消息拆分成独立的词汇
- 为每个指定的数组组,收集它们在消息中的出现位置索引
- 依次检查相邻组的索引范围:前一组的所有词汇的最大出现位置,必须小于后一组所有词汇的最小出现位置——只要这个条件不满足,就说明顺序错乱了
JavaScript 实现代码
function checkOrder(message, groups) { // 拆分消息为词汇数组,处理多空格情况,可按需添加标点清理 const words = message.trim().split(/\s+/); // 为每个组收集所有匹配词汇的索引 const groupIndices = groups.map(group => { const indices = []; group.forEach(word => { const index = words.indexOf(word); if (index !== -1) indices.push(index); }); // 如果组内无匹配词汇,这里返回null,可根据需求调整(比如返回空数组) return indices.length ? indices : null; }); // 遍历检查相邻组的顺序合法性 for (let i = 0; i < groupIndices.length - 1; i++) { const currentGroup = groupIndices[i]; const nextGroup = groupIndices[i + 1]; // 若当前组或下一组无匹配词汇,直接返回false(可按需修改规则) if (!currentGroup || !nextGroup) return false; // 取当前组的最大索引、下一组的最小索引 const maxCurrentIndex = Math.max(...currentGroup); const minNextIndex = Math.min(...nextGroup); // 只要前组有词汇出现在后组词汇之后,就返回false if (maxCurrentIndex >= minNextIndex) return false; } // 所有组顺序都符合要求 return true; }
测试你的示例场景
// 场景1:符合顺序 -> 返回true console.log(checkOrder('hi john', [['hi'], ['john']])); // 场景2:顺序错乱 -> 返回false console.log(checkOrder('john hi', [['hi'], ['john']])); // 场景3:多词汇组符合顺序 -> 返回true console.log(checkOrder('and hey evan', [['and', 'hey'], ['evan']])); // 扩展场景:多组校验 console.log(checkOrder('hello foo world bar', [['hello'], ['foo'], ['world'], ['bar']])); // true console.log(checkOrder('hello world foo bar', [['hello'], ['foo'], ['world'], ['bar']])); // false
可调整的细节
- 标点处理:如果消息里有标点(比如
hi, john),可以先清理标点再拆分:const cleanedMessage = message.replace(/[^\w\s]/g, ''); const words = cleanedMessage.trim().split(/\s+/); - 可选组支持:如果允许某些组的词汇不出现,可以修改
groupIndices的处理逻辑,跳过空索引的组 - 大小写不敏感:如果需要忽略大小写,可以在匹配时统一转成小写:
const lowerWords = words.map(word => word.toLowerCase()); const index = lowerWords.indexOf(word.toLowerCase());
内容的提问来源于stack exchange,提问作者Gatitos Mansion
相关产品推荐
相关产品推荐

