gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:49:18 25 4
gpt4 key购买 nike

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

最佳答案

以下将是更好的解决方案:

return [firstName, lastName].filter(it => !!it).join(" ") || null

请注意,这还将包括“”作为 null/undefined,如果您只提供一个而不提供另一个,请避免在字符串中包括“null”。一般来说,这可能是您正在编写的函数所需要的。

例如:getFullName("John", null) 将返回“John”

关于JavaScript 如何连接两个 null 或 undefined 并返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com