// 传统 if 语句 if (x) { x = y; } // 使用逻辑与配合赋值 x = x && y; // 现代写法(ES2021 起) x &&= y;&&= 如何保持“紧凑而安全”
let access = true; access &&= 'granted'; // access 变为 'granted' access = false; access &&= 'granted'; // access 仍为 false(不更新) access = ''; access &&= 'granted'; // access 仍为空字符串(不更新) access = 0; access &&= 'granted'; // access 仍为 0(不更新)规律?只有当左值是 truthy 时,&&= 才会更新;遇到 falsy 则完全跳过。
function updateUserAccess(user) { // 仅当字段已为 truthy 时才更新权限(避免把 false/空值误改) user.canEdit &&= checkPermissions(); user.canDelete &&= checkAdminStatus(); return user; }示例 2:表单校验
const form = { isValid: true, isSubmitted: false, hasErrors: false }; // 只有在当前判定有效时才继续深入校验 form.isValid &&= validateFields(); // 运行校验并更新 isValid form.isSubmitted &&= submitToServer(); // 若还未提交(falsy)则跳过 form.hasErrors &&= checkErrors(); // 保持 false,不误触发为 true示例 3:API 响应验证链
const response = { isAuthenticated: true, hasPermission: true, isExpired: false }; // 各步骤仅在前置条件为 truthy 时才继续 response.isAuthenticated &&= validateToken(); response.hasPermission &&= checkAccess(); response.isExpired &&= checkExpiration(); // 保持 false(不更新)Pro tip: 别把 &&= 和 ||= 搞混了。||= 是“左值为 falsy 才赋值”,而 &&= 是“左值为 truthy 才赋值”。
可读性:对团队而言,x &&= y 往往比 x = x && y 更直观,但请确保团队成员都熟悉这一语法(ES2021)。