JavaScript如何连接两个null或undefined并返回null

假设值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(无需编写函数)?


慕森王
浏览 153回答 3
3回答

慕尼黑8549860

以下是更好的解决方案:return [firstName, lastName].filter(it => !!it).join(" ") || null请注意,这还将在空/未定义中包含“”,并且如果您提供一个而不提供另一个,则避免在字符串中包含“ null”。通常,这对于您正在编写的功能可能是理想的。例如:getFullName("John", null)将返回“约翰”

慕的地8271018

这是少数使用松散相等运算符(因为null和undefined彼此松散相等,但对别的枚举相等)有益的情况之一。然后,您可以将条件简化为:const getFullName = (firstName, lastName ) => {    if (firstName == null && lastName == null) {        return null;    } else {         return firstName + ' ' + lastName    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript