如果 JavaScript 中未定义,则设置变量
我知道我可以测试 JavaScript 变量,然后定义它(如果它是未定义
),但是有没有某种说法
var setVariable = localStorage.getItem('value') || 0;
似乎是一种更清晰的方式,而且我很确定我已经在其他语言中看到过这个。
I know that I can test for a JavaScript variable and then define it if it is undefined
, but is there not some way of saying
var setVariable = localStorage.getItem('value') || 0;
seems like a much clearer way, and I'm pretty sure I've seen this in other languages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
今天也遇到了这种情况,我不想让多个值覆盖零。我们有一个文件,其中包含一些适用于此类场景的常用实用方法。以下是我为了处理场景并保持灵活性而添加的内容。
如果我只想设置未定义的值或覆盖 null 或 0 值,则可以调用它,最后两个参数是可选的。下面是一个调用示例,如果 ID 未定义或为 null,则将 ID 设置为 -1,但不会覆盖 0 值。
Ran into this scenario today as well where I didn't want zero to be overwritten for several values. We have a file with some common utility methods for scenarios like this. Here's what I added to handle the scenario and be flexible.
It can then be called with the last two parameters being optional if I want to only set for undefined values or also overwrite null or 0 values. Here's an example of a call to it that will set the ID to -1 if the ID is undefined or null, but wont overwrite a 0 value.
即使默认值是布尔值也可以工作:
Works even if the default value is a boolean value:
在我看来,对于当前的 javascript 实现来说,
这是一个很好的方法(使用对象解构)。
正如 mdn 中所述,在这种情况下,只有当该值未定义时才会使用默认值,而如果它仅仅是假值或空值,则不会使用默认值。
It seems to me, that for current javascript implementations,
is a nice way to do this (using object deconstruction).
As noted on mdn, in this case the default value really is only used if the value is undefined, not if it is merely falsy or null.
是的,它可以做到这一点,但严格来说,如果检索到的值为虚假的,而不是真正的未定义。因此,它不仅会匹配
undefined
,还会匹配null
、false
、0
、NaN
>、""
(但不是"0"
)。如果您只想在变量严格
未定义
时设置为默认值,那么最安全的方法是编写:在较新的浏览器上,编写实际上是安全的:
但请注意,在较旧的浏览器上可能会破坏此设置浏览器允许声明一个名为
undefined
的变量,该变量具有已定义的值,从而导致测试失败。Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match
undefined
but alsonull
,false
,0
,NaN
,""
(but not"0"
).If you want to set to default only if the variable is strictly
undefined
then the safest way is to write:On newer browsers it's actually safe to write:
but be aware that it is possible to subvert this on older browsers where it was permitted to declare a variable named
undefined
that has a defined value, causing the test to fail.逻辑空赋值,ES2021+ 解决方案
当前正在向浏览器添加新运算符,
??=
、||=
和&&=
>。这篇文章将重点关注??=
。这会检查左侧是否未定义或为空,如果已定义则短路。如果不是,则将右侧变量分配给左侧变量。
比较方法
基本示例
对象/数组示例
??= 浏览器支持 2022 年 10 月 - 93%
??= Mozilla 文档
||= Mozilla 文档
&&= Mozilla 文档
Logical nullish assignment, ES2021+ solution
New operators are currently being added to the browsers,
??=
,||=
, and&&=
. This post will focus on??=
.This checks if left side is
undefined
ornull
, short-circuiting if already defined. If not, the right-side is assigned to the left-side variable.Comparing Methods
Basic Examples
Object/Array Examples
??= Browser Support Oct 2022 - 93%
??= Mozilla Documentation
||= Mozilla Documentation
&&= Mozilla Documentation
2018 ES6 的答案是:
如果变量 x 未定义,则返回变量 y...否则如果变量 x 已定义,则返回变量 x。
The 2018 ES6 answer is:
If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.
ES2020 答案
使用 Nullish Coalescing 运算符,您如果
value
为 null 或未定义,可以设置默认值。但是,您应该注意,空合并运算符不会返回其他类型的假值(例如
0
和''
)的默认值。不过,请注意浏览器支持。您可能需要使用像 Babel 这样的 JavaScript 编译器将其转换为更向后兼容的东西。如果您使用 Node.js,则 自版本起就支持它14.。
ES2020 Answer
With the Nullish Coalescing Operator, you can set a default value if
value
is null or undefined.However, you should be aware that the nullish coalescing operator does not return the default value for other types of falsy value such as
0
and''
.However, do take note of the browser support. You may need to use a JavaScript compiler like Babel to convert it into something more backward compatible. If you are using Node.js, it has been supported since version 14.
我需要在几个地方“如果未定义则设置一个变量”。我使用@Alnitak 答案创建了一个函数。希望它能帮助某人。
用法:
I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.
Usage:
在我们这个时代,你实际上可以用 JS 来实现你的方法:
所以你的例子会起作用:
In our days you actually can do your approach with JS:
So your example WILL work:
检查
typeof
而不是undefined
似乎更合乎逻辑?我假设您在未定义时将 var 设置为0
时期望一个数字:在这种情况下,如果
getVariable
不是数字(字符串、对象等),则设置 setVariable至0
It seems more logical to check
typeof
instead ofundefined
? I assume you expect a number as you set the var to0
when undefined:In this case if
getVariable
is not a number (string, object, whatever), setVariable is set to0
您可以使用以下任何一种方式。
ES12 或之后
You can use any of below ways.
in ES12 or after
如果您是 FP (函数式编程) 粉丝,Ramda 有一个简洁的辅助函数,称为 defaultTo :
用法:
const result = defaultTo(30)(value)
在处理
未定义
布尔值时更有用:const result2 = defaultTo (假)(dashboard.someValue)
If you're a FP (functional programming) fan, Ramda has a neat helper function for this called defaultTo :
usage:
const result = defaultTo(30)(value)
It's more useful when dealing with
undefined
boolean values:const result2 = defaultTo(false)(dashboard.someValue)
var setVariable = (typeof localStorage.getItem('value') !== '未定义' && localStorage.getItem('value')) || 0;
var setVariable = (typeof localStorage.getItem('value') !== 'undefined' && localStorage.getItem('value')) || 0;