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

React中检查字符串/字符串数组长度的函数优化咨询

React字符串长度校验函数优化方案

需求背景

开发React应用时,部分页面提交数据到API需要满足:提交的字符串(单个或数组)全部符合指定长度。需要实现一个函数:

  • 接收指定长度、单个字符串或字符串数组
  • 全部符合长度则返回true,否则用react-toastify提示错误并返回false
  • 未来可能扩展功能(比如显示首个不符合长度的字符串)

现有实现代码

export const CheckCodeLength = (requiredLength: number, codeToCheck?: string, listOfCodes?: string[]) => {
    if (codeToCheck)
    {
        if (codeToCheck.length === requiredLength) return true;
        toast.error(Resources.Toasts.incorrectCodeLength());
        return false;
    }

    if (listOfCodes)
    {
        if (listOfCodes.filter(code => code.length === requiredLength).length === 0) return true;
        toast.error(Resources.Toasts.incorrectCodeLength());
        return false;
    }
}

ChatGPT给出的参考实现(已翻译,原用console.log替代提示)

function checkStringLength(length, input) {
  if (typeof input === 'string') {
    if (input.length !== length) {
      console.log('字符串长度不匹配:', input);
    }
  } else if (Array.isArray(input)) {
    for (let i = 0; i < input.length; i++) {
      if (input[i].length !== length) {
        console.log('索引', i, '处字符串长度不匹配:', input[i]);
      }
    }
  } else {
    console.log('无效输入类型');
  }
}

优化建议

1. 统一参数结构,避免歧义

原函数用两个可选参数区分单个字符串和数组,容易出现参数传递错误(比如同时传两个参数)。建议合并为一个input参数,自动判断类型:

export const checkCodeLength = (requiredLength: number, input?: string | string[]) => {
  // 处理逻辑
}

2. 修复数组校验逻辑错误

原代码数组校验逻辑完全反转:listOfCodes.filter(code => code.length === requiredLength).length === 0 表示没有一个符合长度时返回true,和需求“全部符合才返回true”完全相反。正确逻辑应该是检查是否存在不符合长度的元素,且用find替代filter更高效(找到第一个不符合项就停止遍历):

const invalidCode = listOfCodes.find(code => code.length !== requiredLength);
if (!invalidCode) return true; // 全部符合要求
toast.error(Resources.Toasts.incorrectCodeLength());
return false;

3. 完善输入校验

原函数未处理空输入和非法类型输入的情况,会导致函数无返回值或逻辑异常:

if (!input) {
  toast.error('请传入需要校验的内容');
  return false;
}

if (typeof input !== 'string' && !Array.isArray(input)) {
  toast.error('输入类型无效,请传入字符串或字符串数组');
  return false;
}

4. 为未来扩展预留接口

如果要实现“显示首个不符合长度的字符串”,可以抽离错误信息生成逻辑,方便后续修改:

const getErrorMsg = (invalidStr?: string, index?: number) => {
  if (invalidStr) {
    return index !== undefined 
      ? `索引${index}处的字符串长度不符合要求:${invalidStr}`
      : `字符串长度不符合要求:${invalidStr}`;
  }
  return Resources.Toasts.incorrectCodeLength();
};

// 使用示例
toast.error(getErrorMsg(invalidCode, invalidIndex));

5. 遵循命名规范

函数名改用小驼峰checkCodeLength,符合TS/JS的通用命名习惯。

完整优化后的代码

import { toast } from 'react-toastify';
import Resources from './path-to-your-resources'; // 替换为实际资源路径

export const checkCodeLength = (requiredLength: number, input?: string | string[]) => {
  // 处理空输入
  if (!input) {
    toast.error('请传入需要校验的内容');
    return false;
  }

  // 校验输入类型
  if (typeof input !== 'string' && !Array.isArray(input)) {
    toast.error('输入类型无效,请传入字符串或字符串数组');
    return false;
  }

  // 处理单个字符串
  if (typeof input === 'string') {
    if (input.length === requiredLength) return true;
    toast.error(`字符串长度不符合要求,需要${requiredLength}位`);
    return false;
  }

  // 处理字符串数组
  let invalidIndex: number | undefined;
  const invalidItem = input.find((code, index) => {
    if (typeof code !== 'string') {
      invalidIndex = index;
      return true;
    }
    if (code.length !== requiredLength) {
      invalidIndex = index;
      return true;
    }
    return false;
  });

  if (!invalidItem) return true;

  // 生成对应错误提示
  if (invalidIndex !== undefined) {
    if (typeof invalidItem !== 'string') {
      toast.error(`索引${invalidIndex}处不是有效字符串`);
    } else {
      toast.error(`索引${invalidIndex}处的字符串长度不符合要求,需要${requiredLength}位`);
    }
  }
  return false;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:52:49