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

JS中如何在switch case内同时校验repeatChecked与validCheked两个变量

问题分析

你原有代码的switch写法存在逻辑错误:

  • switch 传入的判断值是repeatChecked,只会匹配该变量的布尔结果,匹配到对应case就会直接return,validCheked相关的case永远不会执行
  • case 语句中写validCheked = true是赋值操作,不是等值判断,不符合语法要求

实现方案(switch 写法)

如果一定要通过switch处理两个布尔变量的校验,可以使用switch(true)的写法,按错误优先级排列case即可,实现逻辑如下:

export const checked = (e, options) => {
  const nameCheked = new RegExp("^[a-zA-Z0-9]{1,50}$");
  const repeatChecked = options.every(
    (pool) => pool.text.toLowerCase() !== e.target.value.toLowerCase()
  );
  const validCheked = nameCheked.test(e.target.value);

  // 用switch(true)匹配第一个为真的case条件
  switch (true) {
    // 优先级高的错误放前面,示例先判断格式是否合法
    case !validCheked:
      return {
        type: false,
        text: "Invalid name (no special character)"
      };
    // 再判断是否重复
    case !repeatChecked:
      return {
        type: false,
        text: "repeatName"
      };
    // 两个校验都通过走成功逻辑
    default:
      return {
        type: true,
        text: "looks good"
      };
  }
}

注意:如果两个校验同时不通过,排在前面的case会先触发,你可以根据业务需求调整两个case的前后顺序。


补充说明

如果不强制要求用switch,直接用if判断代码可读性会更高,和上述switch写法逻辑完全一致:

export const checked = (e, options) => {
  const nameCheked = new RegExp("^[a-zA-Z0-9]{1,50}$");
  const repeatChecked = options.every(
    (pool) => pool.text.toLowerCase() !== e.target.value.toLowerCase()
  );
  const validCheked = nameCheked.test(e.target.value);

  if (!validCheked) {
    return { type: false, text: "Invalid name (no special character)" };
  }
  if (!repeatChecked) {
    return { type: false, text: "repeatName" };
  }
  return { type: true, text: "looks good" };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:36:03