JavaScript:使用条件语句进行解构

时间:2018-10-19 13:23:38

标签: javascript ecmascript-6

我想从整个firstName对象获得lastNameuser属性。我也需要使用条件语句。 该怎么做?

getUserById(id)getUserByAddress(id)使用JavaScript find()方法返回元素或undefined

let { firstName, lastName } = getUserById(id);
if ({ firstName, lastName } === undefined) {
  { firstName, lastName } = getUserByAddress(id);
}
return `${firstName} ${lastName}`;

1 个答案:

答案 0 :(得分:13)

const { firstName, lastName } = getUserById(id) || getUserByAddress(id) || {};
if (firstName && lastName) {
    return `${firstName} ${lastName}`;
}
return "Unknown user";

如果getUserById(id)虚假,将执行getUserByAddress(id)。如果这也是虚假的,{}至少将防止引发错误。