![](/img/trans.png)
[英]JavaScript checking for null vs. undefined and difference between == and ===
[英]Typescript: what's the difference between checking if a variable is empty vs. checking if it has a value?
我正在向我的代碼添加驗證,並且為了提高可讀性,寫了以下內容:
if (!uid) {
return {result: 0, message: 'You are not authorized.'}
}
另一種方法是檢查變量是否存在:
if (uid) {
//do some code
}
但是,如果我有很多不同的變量要驗證,我不喜歡像這樣嵌套它們:
if (uid) {
if (otherVar) {
//do some code
} else {
//else code 1
}
} else {
//else code 2
}
做方法1和方法2有什么區別嗎?
答案:
true
,那么它將返回true
。true
。我的意見,你實際上不必那樣做。 相反,您可以使用可選的鏈接運算符來在 object 內部進行安全檢查。 例如:
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name; // notice the usage of '?'
console.log(dogName); // will return 'undefined' as 'dog' object does not exist in that object.
引用 MDN 文檔:
這?。 運算符的功能類似於。 鏈接運算符,除了如果引用為空(null 或未定義)時不會導致錯誤,表達式會短路並返回未定義的值。 當與 function 調用一起使用時,如果給定的 function 不存在,則返回 undefined。
從那里,您可以使用可選鏈接來簡化嵌套塊 - 就像使用全局錯誤處理程序一樣。
const result = uid?.otherVar?; // imagine 'otherVar' does not exist!
if (!result) return handleResult();
進一步閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.