You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统一数组元素大小写并优化元素推入的校验逻辑?

解决大小写不敏感的单词校验问题

核心思路是在校验时统一转换为小写(或大写)进行比较,但数组仍存储用户输入的原始格式,这样既保证校验逻辑不受大小写影响,又能保留输入的原样。

修改后的完整JS代码:

const field = document.querySelector('#field');
const message = document.querySelector('#message');
const playBtn = document.querySelector('#play')

let usedCities = [];

playBtn.addEventListener('click', function() {
    const inputValue = field.value.trim();
    // 生成输入值的小写版本,用于校验
    const inputLower = inputValue.toLowerCase();

    // 数组为空时直接校验通过
    if (!usedCities.length) {
        usedCities.push(inputValue);
        field.value = '';
        message.textContent = '';
        console.log(usedCities);
        return;
    }

    const lastWordInArray = usedCities[usedCities.length - 1];
    // 检查输入是否已存在(大小写不敏感)
    const isDuplicate = usedCities.some(city => city.toLowerCase() === inputLower);
    // 检查首字母是否匹配最后一个元素的尾字母(大小写不敏感)
    const matchesLastLetter = lastWordInArray.toLowerCase().slice(-1) === inputLower[0];

    if (!isDuplicate && matchesLastLetter) {
        usedCities.push(inputValue);
        message.textContent = '';
    } else {
        // 错误提示
        if (isDuplicate) {
            message.textContent = '该单词已存在!';
        } else {
            message.textContent = '首字母与上一个单词的尾字母不匹配!';
        }
    }

    field.value = '';
    console.log(usedCities);
})

关键改动说明

  • 统一大小写校验:所有用于比较的字符串都转换为小写,避免"Maine"和"maine"被判定为不同单词,同时"Maine"的尾字母e(转小写后)能和"Egypt"的首字母E(转小写后)匹配。
  • 替换includes为some:includes是严格匹配大小写的,改用some配合toLowerCase()实现大小写不敏感的重复检查。
  • 修正逻辑优先级:原代码中||和&&的优先级可能导致逻辑错误,现在拆分逻辑并明确判断顺序,同时添加了错误提示提升用户体验。
  • 输入处理:添加trim()去除输入首尾空格,避免空输入或空格干扰校验。

内容的提问来源于stack exchange,提问作者Axnyc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:16:15