如果未定义,javascript 设置一个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5409641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:04:19  来源:igfitidea点击:

javascript set a variable if undefined

javascriptundefined

提问by pedalpete

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

我知道我可以测试一个 javascript 变量,然后在它未定义的情况下定义它,但是有没有办法说

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

seems like a much clearer way, and I'm pretty sure I've seen this in other languages.

似乎是一种更清晰的方式,而且我很确定我已经在其他语言中看到过这一点。

回答by Alnitak

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 undefinedbut also null, false, 0, NaN, ""(but not"0").

是的,它可以做到这一点,但严格来说,如果检索到的值为falsey,而不是真正的undefined,它将分配默认值。因此,它不仅会匹配,undefined而且还会匹配null, false, 0, NaN, ""(但不是"0")。

If you want to set to default only if the variable is strictly undefinedthen the safest way is to write:

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

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 undefinedthat has a defined value, causing the test to fail.

但请注意,在允许声明undefined具有定义值的命名变量的旧浏览器上,可能会破坏这一点,从而导致测试失败。

回答by Sterling Bourne

The 2018 ES6 answer is:

2018 ES6 的答案是

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

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

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

回答by Bruno

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

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

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

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

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

回答by Mcestone

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

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

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

Usage:

用法:

hasPoints = setDefaultVal(this.hasPoints, true);

回答by wentjun

ES2020 Answer

ES2020 答案

With the Nullish CoalescingOperator, you can set a default value if valueis null or undefined.

使用Nullish CoalescingOperator,您可以设置默认值(如果value为 null 或未定义)。

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 0and ''.

但是,您应该知道空合并运算符不会返回其他类型的假值(例如0and )的默认值''

Do take note that browser support for the operator is limited. According to the data from caniuse, only 48.34% of browsers are supported (as of April 2020). Node.js support was added in version 14.

请注意,对运营商的浏览器支持是有限的。根据caniuse的数据,仅支持 48.34% 的浏览器(截至 2020 年 4 月)。版本 14添加了Node.js 支持。

回答by Damian Green

If you're a FP (functional programming) fan, Ramdahas a neat helper function for this called defaultTo:

如果你是 FP(函数式编程)爱好者,Ramda有一个简洁的辅助函数,名为defaultTo

usage:

用法:

const result = defaultTo(30)(value)

const result = defaultTo(30)(value)

It's more useful when dealing with undefinedboolean values:

在处理undefined布尔值时更有用:

const result2 = defaultTo(false)(dashboard.someValue)

const result2 = defaultTo(false)(dashboard.someValue)

回答by Zikes

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

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

回答by Mark Seefeldt

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.

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

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

回答by Tsz Lam Yau

Works even if the default value is a boolean value:

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

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

回答by T S

It seems to me, that for current javascript implementations,

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

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

is a nice way to do this (using object deconstruction).

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