由于代码写太快,又踩了个雷
const temp1 = this.tagList.filter(i => {this.labs.includes(i.tagName)
})const temp2 = this.tagList.filter(item => this.labs.includes(item.tagName)
);console.log(temp1) // []
console.log(temp2) // [{...}]
temp1 一直没有返回数据,把代码发给deepseek,才发现是 JavaScript 箭头函数的隐式返回规则...
箭头函数的返回值机制
当箭头函数使用大括号 {} 时,它变成了一个代码块,此时必须显式使用 return 来返回值
代码没有 return,所以函数默认返回 undefined(相当于 false),导致 filter() 没有保留任何元素
temp1 的代码等于
const temp1 = this.tagList.filter(i => {this.form.labs.includes(i.tagName);return undefined; // 默认行为
});
当箭头函数省略大括号 {} 时,它会隐式返回单行表达式的结果 includes() 值
temp2 的代码等于
const temp = this.tagList.filter(item => {return this.form.labs.includes(item.tagName); // 显式返回
});
根本原因:箭头函数的大括号 {} 是否使用导致了返回值差异