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

处理JSON时如何为falsy输入设置回退?以jQuery获取authorities为例

简洁实现选中/隐藏authorities值的回退逻辑

问题背景

需要实现的逻辑:无法确定页面是否存在选中的authorities元素,若存在则取选中项的值;若不存在,则取所有authorities元素(实际为隐藏输入框)的值。

原代码失效原因:尝试用JS真值/假值逻辑编写的代码无法正常运行,因为当:checked选择器未匹配到元素时,val()返回undefined,直接传入JSON.parse()会抛出语法异常,代码中断后无法触发后续的||回退逻辑。


解决方案

核心思路是先获取到有效的字符串值,再统一执行JSON解析,避免在||两侧单独调用JSON.parse()导致异常中断,同时保持代码简洁无需额外条件判断。

简洁实现代码

let user = {
    id: $(this).find('[name=id]').val(),
    username: $(this).find('[name=username]').val(),
    password: $(this).find('[name=password]').val(),
    name: $(this).find('[name=name]').val(),
    lastName: $(this).find('[name=lastName]').val(),
    department: $(this).find('[name=department]').val(),
    salary: $(this).find('[name=salary]').val(),
    age: $(this).find('[name=age]').val(),
    email: $(this).find('[name=email]').val(),
    enabledByte: $(this).find('[name=enabledByte]').val(),
    authorities: JSON.parse(
        // 优先取选中的authorities值,否则取所有authorities的值,最后兜底空数组
        $(this).find('[name=authorities]:checked').val() || 
        $(this).find('[name=authorities]').val() ||
        '[]'
    )
};

逻辑说明

  1. 通过||运算符依次尝试获取值:
    • 优先匹配选中的authorities元素并取值
    • 无选中项时,匹配所有authorities元素取值
    • 若两种情况都未匹配到,用'[]'作为兜底默认值
  2. 将最终拿到的有效字符串传入JSON.parse(),彻底避免undefined导致的解析异常
  3. 全程无需额外的if判断语句,保持代码紧凑简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:07:39