2 回答

TA贡献1862条经验 获得超6个赞
一些自称的最佳实践:
当您不需要索引时,尽可能避免使用 for 循环。(参见forEach等)。这样可以减少污染眼睛的变量。
尽早“继续”或“返回”以避免嵌套内容(例如
return links
先出现)尽量减少变量的范围。这也是通过使用 forEach 来实现的
function nameTooLong(data, existingLinks, linkSetter) {
const moreLinks = data.reduce((links, item) => {
if (item.activitiesafter[0] === "DEFAULT") {
return links
}
item.activitiesafter.forEach(activity => {
links.push({
source: item.itemname,
target: activity,
type: "activity-activity-after"
})
})
return links
}, [])
return linkSetter(_ => existingLinks.concat(moreLinks))
}
nameTooLong([{
itemname: "Hello World",
itemtype: "activity",
activitiesafter: ["Do Stuff", "Do Other Stuff"]
},{
itemname: "shold be ignored",
itemtype: "activity",
activitiesafter: ["DEFAULT", "nothing there"]
}], ['toto'], (fn) => console.log('newlinks: ', fn()))
如果您阅读 3.,我们可以做得更好,甚至可以避免使用flatMap操作变量链接
function nameTooLong(data, existingLinks, linkSetter) {
const moreLinks = data.flatMap(item => {
if (item.activitiesafter[0] === "DEFAULT") {
return []
}
return item.activitiesafter.map(activity => ({
source: item.itemname,
target: activity,
type: "activity-activity-after"
}))
})
return linkSetter(_ => existingLinks.concat(moreLinks))
}
nameTooLong([{
itemname: "Hello World",
itemtype: "activity",
activitiesafter: ["Do Stuff", "Do Other Stuff"]
},{
itemname: "shold be ignored",
itemtype: "activity",
activitiesafter: ["DEFAULT", "nothing there"]
}], ['toto'], (fn) => console.log('newlinks: ', fn()))

TA贡献1712条经验 获得超3个赞
push 函数仅适用于数组,不适用于对象。
而且由于我认为没有任何理由linkLineItems
需要成为一个对象,我建议您只需通过初始化它来使其成为一个数组let linkLineItems = [];
。
添加回答
举报