我试图显示一个名称,但发现连接未定义的字符串很困难。
如果要显示displayName
或将firstName
和lastName
连接起来,我想显示它,或者不显示defaultName
则显示它。
如果我的变量存在
let displayName = "John Doe";
let firstName = "Super";
let lastName = "Man";
let defaultName = "NIL";
console.log(displayName || firstName + " " + lastName || defaultName);
Output: John Doe
如果变量为undefined
let displayName = undefined;
let firstName = undefined;
let lastName = undefined;
let defaultName = "NIL";
console.log(displayName || firstName + " " + lastName || defaultName);
Output: undefined undefined
当没有whitespace
时它就可以工作,因为它像arithmetic operator
一样对待,但是由于缺少SuperMan
,输出将是whitespace
。
我该如何解决?
答案 0 :(得分:4)
这假设只有firstName和lastName都具有值,您才希望第二个选项显示,否则显示defaultName
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
您的let displayName = undefined;
let firstName = undefined;
let lastName = undefined;
let defaultName = "NIL";
console.log(displayName ? displayName : firstName && lastName ? `${firstName} ${lastName}` : defaultName);
总是会返回一个值,该值在JavaScript中将被评估为true,这就是您当前看到的内容的原因。
答案 1 :(得分:1)
关于'foo'+ +'foo'的队列笑话。
A || javascript中的B真正的意思是“如果A是真实的,则传递A。否则,传递B”。并且类型不在窗口之内,JavaScript会尝试将其连接到一个错误。系统中的最终扳手是奇怪的操作顺序。
displayName || firstName + " " + lastName || defaultName
(displayName || firstName) + ((" " + lastName) || defaultName)
( undefined ) + (" undefined" || defaultName)
undefined + " undefined"
"undefined undefined"
如果您想正确执行此操作,则有很多不错的选择。我会说类似
function forceGoodString(input) {
if (typeof input === "string" && input.length) {
return input;
} else {
return "";
}
}
...我实际上不确定使用三个未定义的变量“ NIL”还是仅仅是“ NIL”会得到什么?无论如何,您还需要几行。可读性没有错,并非所有内容都必须花哨${garbage}
和三元数衬里。
if (displayName) {
console.log(displayName);
} else if (firstName && lastName) {
console.log(firstName + " " + lastName);
} else {
console.log(defaultName);
}
如果您对JS中的松散类型感到厌倦,您可以随时学习go!
答案 2 :(得分:1)
...尊重operator precedence,并利用type casting以及truthy和falsy值...
let displayName;
let firstName;
let lastName;
let defaultName = 'NIL';
console.log(
displayName
|| ((firstName || '') + ' ' + (lastName || '')).trim()
|| defaultName
);
displayName = '';
firstName = 'John';
console.log(
displayName
|| ((firstName || '') + ' ' + (lastName || '')).trim()
|| defaultName
);
displayName = '';
firstName = '';
lastName = 'Doe';
console.log(
displayName
|| ((firstName || '') + ' ' + (lastName || '')).trim()
|| defaultName
);
displayName = '';
firstName = 'John';
console.log(
displayName
|| ((firstName || '') + ' ' + (lastName || '')).trim()
|| defaultName
);
displayName = '';
firstName = '';
lastName = '';
console.log(
displayName
|| ((firstName || '') + ' ' + (lastName || '')).trim()
|| defaultName
);
.as-console-wrapper { max-height: 100%!important; top: 0; }