如何避免在JavaScript reduce回调中重复声明工具函数?
优化方案
直接将getStudentLabel函数定义移到reduce回调的外层作用域即可。这个函数本身不依赖reduce回调内部的局部变量,完全可以独立声明,全局只初始化一次,每次reduce迭代时直接调用即可,不会重复创建函数实例。
优化后代码示例
// 函数仅声明一次,可在当前作用域内复用 const getStudentLabel = (student) => { if (student.groupName) { return [student.name, `(${student.groupName})`].join(' '); } return student.name; }; const idsToStudents = allStudents.reduce((tempMap, student) => { return { ...tempMap, [student.id]: { ...student, label: getStudentLabel(student) } }; }, {});
额外可选精简方案
如果后续不需要复用getStudentLabel,也可以直接内联label的计算逻辑,代码更简洁:
const idsToStudents = allStudents.reduce((tempMap, student) => { return { ...tempMap, [student.id]: { ...student, label: student.groupName ? `${student.name} (${student.groupName})` : student.name } }; }, {});
内容的提问来源于stack exchange,提问作者spspli
相关产品推荐
相关产品推荐

