我有这段代码:
var sideBar = localStorage.getItem('Sidebar');
我想检查 sideBar 是否在 if 语句中被定义且不为 null。我有点困惑,我知道:sideBar == undefined
和 sideBar != null
,但是否有一个好的方法可以在 if 语句中同时检测这两个条件:
if (??)
我有这段代码:
var sideBar = localStorage.getItem('Sidebar');
我想检查 sideBar 是否在 if 语句中被定义且不为 null。我有点困惑,我知道:sideBar == undefined
和 sideBar != null
,但是否有一个好的方法可以在 if 语句中同时检测这两个条件:
if (??)
检查变量是否已定义且不为null的最佳实践:
if (typeof sideBar !== 'undefined' && sideBar !== null)
编辑:我意识到您检查的不是未定义的内容,而是检查它是否被定义,因此再次进行了编辑以更准确地回答您的请求。
!== null
返回true。 - DjangoDev1if (!!token && token.trim() !== 'undefined') {...}
。这段代码检查了null
、undefined
、""
(空字符串)以及键的值为'undefined'
(一个字符串)的情况。 - MikhailRatnerif (localStorage.getItem("Sidebar") !== null) {
//...
}
undefined
,因为它不存在于localStorage.getItem方法的返回值中。 - xgqfrmslocalStorage
使用字符串来保存数据,即您在考虑 null
vs. undefined
等时总是要考虑 JavaScript 字符串逻辑。""
才是“falsy”值。如果您在变量进行 if
检查之前执行其他操作(例如一些数学运算),则需要考虑其他情况。以下是一些测试,展示了JavaScript在if语句中处理某些值的方式:
> ("")? true : false
false # empty string -> if fails
> (0)? true : false
false # Number 0 -> if fails
> ("0")? true : false
true # String "0" -> if succeeds
> (null)? true : false
false # JavaScript null -> if fails
> ("someText")? true : false
true # any other String -> if succeeds
> (" ")? true : false
true # a space character -> if succeeds
我不会使用笨拙的双重检查来检查 null
和 undefined
。
如果直接检查 localStorage.getItem
的结果,结果只可能是 null
或者一个 String
。如果你认为空字符串 ""
也是“假”的话,
一个简单的 if
语句就足够了:
var sideBar = localStorage.getItem('Sidebar');
if(sideBar) {
// do something with the sideBar
}
else {
// do something without the sideBar
}
如果要真正检查localStorage中的sideBar是否被设置,您需要添加一个检查空字符串并将其视为“已定义”的检查:
if(sideBar || sideBar === "") {
// sideBar defined, maybe even as empty String
}
else {
// sideBar not set in localStorage
}
String
需要被视为“假值”。 - JuvesideBar !== ""
。 - Juvenullish coalescing
运算符空值合并运算符(
??
)是一个逻辑运算符,当左侧操作数为null或undefined时,返回其右侧操作数,否则返回左侧操作数。
const sideBar = localStorage.getItem('Sidebar') ?? false;
if(sideBar) {
// true
} else {
// false
}
localStorage.getItem
方法时,您不需要检查 undefined
。Storage 接口的 getItem() 方法,当传入一个键名时,将返回该键的值;如果该键不存在,则返回给定 Storage 对象中的 null。
https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
这应该可以工作,但是除了 “if” 之外,即使使用三元运算符也没有其他方式。
if( !value ) {
}
这将检查值是否为“真实”,并应涵盖“null”和“undefined”。
是的,你可以用 &&
把它们绑定在一起(意味着两个条件都必须为真)。
所以... 只有当每个条件都为真时,if (sideBar === undefined && sideBar !== null)
才会被评估为真。
可以使用 && 连接 if 语句。
建议使用 '==='。例如:if (sideBar === undefined && sideBar !== null)
到了2023年,应该改为以下代码:
if (!!token && token.trim() !== 'undefined') {...}
这段代码检查了token的值是否为null
、undefined
、""
(空字符串),以及键的值是否为'undefined'
(字符串形式的undefined)。