JavaScript函数中使用forEach报no-unused-expressions编译错误求助
解决forEach触发
no-unused-expressions编译错误 错误原因
你遇到的Expected an assignment or function call and instead saw an expression no-unused-expressions是ESLint规则no-unused-expressions的报错,问题出在使用可选链?.调用forEach的写法上——forEach本身返回undefined,而data?.forEach(...)这种链式调用会被ESLint判定为无意义的独立表达式,因为它既没有被赋值给变量,也没有作为函数参数使用。
修复方案
把可选链调用?.forEach改成先判断变量是否存在,再调用forEach的写法,就能避开这个规则的限制:
const mapRole = (data, worker = false) => { const byServiceGroup = []; // 先判断data存在,再调用forEach if (data) { data.forEach((obj) => { const { roleName = '', groupCombination = [] } = obj; const serviceGroupIds = groupCombination?.find(({ groupName }) => groupName === 'service_group')?.ids; // 先判断serviceGroupIds存在,再调用forEach if (serviceGroupIds) { serviceGroupIds.forEach((group) => { let path = `/att/${worker ? 'w' : 'en'}/${roleName ? roleName + '/' : ''}ds`; if (group === 'ALL') return; // skipping for 'ALL' byServiceGroup.push({ serviceGroup: group, worker: worker, path: path, userRole: roleName, }); }); } }); } return byServiceGroup; };
替代方案(调整ESLint规则)
如果你不想修改代码结构,也可以在ESLint配置中给no-unused-expressions规则添加例外,允许可选链表达式:
{ "rules": { "no-unused-expressions": ["error", { "allowShortCircuit": true, "allowTernary": true, "allowTaggedTemplates": true, "allowOptionalChaining": true }] } }
不过更推荐第一种代码修改方案,因为它不需要依赖规则调整,代码兼容性更好。
内容的提问来源于stack exchange,提问作者Ashwani Panwar
相关产品推荐
相关产品推荐

