gpt4 book ai didi

javascript - 使用否定守卫

转载 作者:行者123 更新时间:2023-11-28 13:13:07 25 4
gpt4 key购买 nike

是否有更好的方法来编写以下内容?:

t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};

因此,如果定义了用户,那么我希望使用 userId,否则使用 teamId。

    const name = "Me";
const color = "Red";
let user;
let teamId = 10;

t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};

console.log(t)

user = {id: 1};
teamId = undefined;

t = {
name,
color,
teamId: !user?undefined:teamId,
userId: user&&user.id
};

console.log(t)

最佳答案

它仍然有点困惑,但它只检查用户一次并且更具可读性

return user ? { name, color, "userId": user.id } : { name, color, "teamId": teamId };

关于javascript - 使用否定守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40919316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com