[英]Shortcuts for conditional statements in JavaScript
I do have the following variable:我确实有以下变量:
var text = getValue();
getValue()
- can be empty, thus text === undefined, can be === "Example" but also can be === "Hello World. getValue()
- 可以为空,因此 text === undefined,可以是 === "Example" 但也可以是 === "Hello World.
I want to check two things: 1. if text !== undefined AND if text === "Hello World"我想检查两件事:1. if text !== undefined AND if text === "Hello World"
Method for achieving it:实现方法:
if(text !== undefined && text === "Hello World")
Issue : The text variable is typed in twice for two comparisions.问题:为两次比较输入了两次文本变量。
Question : How to check two things(undefined, Hello World) but using text once?问题:如何检查两件事(未定义,Hello World)但只使用一次文本?
EDIT : I did a mistake with the example, check the new variable text;编辑:我在例子中犯了一个错误,检查新的变量文本; Thank you!
谢谢!
text === "Hello World"
implies that it is not undefined
, so it is the only condition needed.意味着它不是
undefined
,所以它是唯一需要的条件。
if (text === "Hello World") { ...
Additional info附加信息
To check if a string has content, you can check:要检查字符串是否有内容,您可以检查:
if (text) { ...
It means the same as:它的含义与以下内容相同:
if (text !== undefined && text !== null && text !== '') { ...
Above answer works, but for more nested property check, use Optional chaining以上答案有效,但要进行更多嵌套属性检查,请使用可选链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.