假設值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(無需編寫函數)?
JavaScript如何連接兩個null或undefined并返回null
慕森王
2021-05-12 13:13:20