前端开发中,使用箭头函数显示返回和隐式返回的区别?
假设后端返回数据为:
const users = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
];
现有两种写法:
第一种:
/*
使用 () 包裹对象字面量
隐式返回,不需要写 return
代码更简洁
*/
const newUsers = users.map(user => ({
...user,
isAdult: user.age >= 18
}));
第二种:
/*
使用 {} 包裹函数体
显式返回,必须写 return
可以写多行逻辑
*/
const transform = users.map(item=>{
return {
id1:item.id,
name1:item.name,
}
}
// 如果你想要重命名且保留其他字段,可以使用如下的写法
{ ...user, id1: user.id, name1: user.name } // 会同时有 id 和 id1

浙公网安备 33010602011771号