如果 JavaScript 中未定义,则设置变量

发布于 2024-10-26 00:33:18 字数 224 浏览 3 评论 0原文

我知道我可以测试 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

一城柳絮吹成雪 2024-11-02 00:33:19

今天也遇到了这种情况,我不想让多个值覆盖零。我们有一个文件,其中包含一些适用于此类场景的常用实用方法。以下是我为了处理场景并保持灵活性而添加的内容。

function getIfNotSet(value, newValue, overwriteNull, overwriteZero) {
    if (typeof (value) === 'undefined') {
        return newValue;
    } else if (value === null && overwriteNull === true) {
        return newValue;
    } else if (value === 0 && overwriteZero === true) {
        return newValue;
    } else {
        return value;
    }
}

如果我只想设置未定义的值或覆盖 null 或 0 值,则可以调用它,最后两个参数是可选的。下面是一个调用示例,如果 ID 未定义或为 null,则将 ID 设置为 -1,但不会覆盖 0 值。

data.ID = Util.getIfNotSet(data.ID, -1, true);

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.

function getIfNotSet(value, newValue, overwriteNull, overwriteZero) {
    if (typeof (value) === 'undefined') {
        return newValue;
    } else if (value === null && overwriteNull === true) {
        return newValue;
    } else if (value === 0 && overwriteZero === true) {
        return newValue;
    } else {
        return value;
    }
}

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.

data.ID = Util.getIfNotSet(data.ID, -1, true);
So尛奶瓶 2024-11-02 00:33:19

即使默认值是布尔值也可以工作:

var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );

Works even if the default value is a boolean value:

var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );
相守太难 2024-11-02 00:33:19

在我看来,对于当前的 javascript 实现来说,

var [result='default']=[possiblyUndefinedValue]

这是一个很好的方法(使用对象解构)。

正如 mdn 中所述,在这种情况下,只有当该值未定义时才会使用默认值,而如果它仅仅是假值或空值,则不会使用默认值。

It seems to me, that for current javascript implementations,

var [result='default']=[possiblyUndefinedValue]

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.

愿得七秒忆 2024-11-02 00:33:18

是的,它可以做到这一点,但严格来说,如果检索到的值为虚假的,而不是真正的未定义。因此,它不仅会匹配 undefined,还会匹配 nullfalse0NaN >、""(但不是"0")。

如果您只想在变量严格未定义时设置为默认值,那么最安全的方法是编写:

var x = (typeof x === 'undefined') ? your_default_value : x;

在较新的浏览器上,编写实际上是安全的:

var x = (x === undefined) ? your_default_value : x;

但请注意,在较旧的浏览器上可能会破坏此设置浏览器允许声明一个名为 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 also null, 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:

var x = (typeof x === 'undefined') ? your_default_value : x;

On newer browsers it's actually safe to write:

var x = (x === undefined) ? your_default_value : x;

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.

椵侞 2024-11-02 00:33:18

逻辑空赋值,ES2021+ 解决方案

当前正在向浏览器添加新运算符,??=||=&&= >。这篇文章将重点关注 ??=

这会检查左侧是否未定义或为空,如果已定义则短路。如果不是,则将右侧变量分配给左侧变量。

比较方法

// Using ??=
name ??= "Dave"

// Previously, ES2020
name = name ?? "Dave"

// or
if (typeof name === "undefined" || name === null) {
    name = true
}

// Before that (not equivalent, but commonly used)
name = name || "Dave" // Now: name ||= "Dave"

基本示例

let a       // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

对象/数组示例

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

??= 浏览器支持 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 or null, short-circuiting if already defined. If not, the right-side is assigned to the left-side variable.

Comparing Methods

// Using ??=
name ??= "Dave"

// Previously, ES2020
name = name ?? "Dave"

// or
if (typeof name === "undefined" || name === null) {
    name = true
}

// Before that (not equivalent, but commonly used)
name = name || "Dave" // Now: name ||= "Dave"

Basic Examples

let a       // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

??= Browser Support Oct 2022 - 93%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

别闹i 2024-11-02 00:33:18

2018 ES6 的答案是

return Object.is(x, undefined) ? y : x;

如果变量 x 未定义,则返回变量 y...否则如果变量 x 已定义,则返回变量 x。

The 2018 ES6 answer is:

return Object.is(x, undefined) ? y : x;

If variable x is undefined, return variable y... otherwise if variable x is defined, return variable x.

空袭的梦i 2024-11-02 00:33:18

ES2020 答案

使用 Nullish Coalescing 运算符,您如果 value 为 null 或未定义,可以设置默认值。

const setVariable = localStorage.getItem('value') ?? 0;

但是,您应该注意,空合并运算符不会返回其他类型的假值(例如 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.

const setVariable = localStorage.getItem('value') ?? 0;

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.

鹿港小镇 2024-11-02 00:33:18

我需要在几个地方“如果未定义则设置一个变量”。我使用@Alnitak 答案创建了一个函数。希望它能帮助某人。

function setDefaultVal(value, defaultValue){
   return (value === undefined) ? defaultValue : value;
}  

用法:

hasPoints = setDefaultVal(this.hasPoints, true);

I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.

function setDefaultVal(value, defaultValue){
   return (value === undefined) ? defaultValue : value;
}  

Usage:

hasPoints = setDefaultVal(this.hasPoints, true);
雄赳赳气昂昂 2024-11-02 00:33:18

在我们这个时代,你实际上可以用 JS 来实现你的方法:

// Your variable is null
// or '', 0, false, undefined
let x = null;

// Set default value
x = x || 'default value';

console.log(x); // default value

所以你的例子会起作用:

const setVariable = localStorage.getItem('value') || 0;

In our days you actually can do your approach with JS:

// Your variable is null
// or '', 0, false, undefined
let x = null;

// Set default value
x = x || 'default value';

console.log(x); // default value

So your example WILL work:

const setVariable = localStorage.getItem('value') || 0;
裂开嘴轻声笑有多痛 2024-11-02 00:33:18

检查 typeof 而不是 undefined 似乎更合乎逻辑?我假设您在未定义时将 var 设置为 0 时期望一个数字:

var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;

在这种情况下,如果 getVariable 不是数字(字符串、对象等),则设置 setVariable至 0

It seems more logical to check typeof instead of undefined? I assume you expect a number as you set the var to 0 when undefined:

var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;

In this case if getVariable is not a number (string, object, whatever), setVariable is set to 0

动次打次papapa 2024-11-02 00:33:18

您可以使用以下任何一种方式。

let x;
let y = 4;
x || (x = y)

ES12 或之后

let x;
let y = 4;
x ||= y;

You can use any of below ways.

let x;
let y = 4;
x || (x = y)

in ES12 or after

let x;
let y = 4;
x ||= y;
忆悲凉 2024-11-02 00:33:18

如果您是 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)

旧时浪漫 2024-11-02 00:33:18

var setVariable = (typeof localStorage.getItem('value') !== '未定义' && localStorage.getItem('value')) || 0;

var setVariable = (typeof localStorage.getItem('value') !== 'undefined' && localStorage.getItem('value')) || 0;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文