假设值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 null
a = {};
console.log("fullName with function is "+JSON.stringify(b.fullName)); // fullName with function is null
有没有更好的方法来使b.fullName的值为null(无需编写函数)?
慕尼黑8549860
慕的地8271018
相关分类