假设值firsName和lastName来自某些数据源。该值有时可能为null或都未定义。fullName将两者结合在一起。let a = {};let b = { fullName: a && a.firstName+' '+a.lastName};console.log("fullName is "+JSON.stringify(b.fullName)); // fullName is "undefined undefined"a = { firstName: null, lastName: null};b = { fullName: a.firstName+' '+a.lastName};console.log("fullName is "+JSON.stringify(b.fullName)); // fullName is "null null"b = { fullName: {...a.firstName, ...' ', ...a.lastName}};console.log("fullName is "+JSON.stringify(b.fullName)); // fullName is {"0":" "}b = { fullName: {...a.firstName, ...a.lastName}};console.log("fullName is "+JSON.stringify(b.fullName)); // fullName is {}我当前的解决方案是const getFullName = (firstName, lastName ) => { if ((typeof firstName == "undefined" || firstName === null) && (typeof lastName == "undefined" || lastName === null)) { return null; } else { return firstName+' '+lastName }}b = { fullName: getFullName(a.firstName, a.lastName)};console.log("fullName with function is "+JSON.stringify(b.fullName)); // fullName with function is nulla = {};console.log("fullName with function is "+JSON.stringify(b.fullName)); // fullName with function is null有没有更好的方法来使b.fullName的值为null(无需编写函数)?
3 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
以下是更好的解决方案:
return [firstName, lastName].filter(it => !!it).join(" ") || null
请注意,这还将在空/未定义中包含“”,并且如果您提供一个而不提供另一个,则避免在字符串中包含“ null”。通常,这对于您正在编写的功能可能是理想的。
例如:getFullName("John", null)
将返回“约翰”
慕的地8271018
TA贡献1796条经验 获得超4个赞
这是少数使用松散相等运算符(因为null和undefined彼此松散相等,但对别的枚举相等)有益的情况之一。然后,您可以将条件简化为:
const getFullName = (firstName, lastName ) => {
if (firstName == null && lastName == null) {
return null;
} else {
return firstName + ' ' + lastName
}
}
添加回答
举报
0/150
提交
取消