javascript设置一个未定义的变量

时间:2022-11-05 20:50:52

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.

看起来更清楚了,我肯定我在其他语言中也见过。

6 个解决方案

#1


251  

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").

是的,它可以这样做,但严格地说,如果检索到的值是falsey,那么它将分配默认值,而不是真正未定义的值。因此,它不仅匹配未定义的,而且还匹配null, false, 0, NaN,“”(但不是“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') ? def_val : x;

On newer browsers it's actually safe to write:

在更新的浏览器上,写:

var x = (x === undefined) ? def_val : 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.

但是要注意的是,在旧的浏览器上有可能破坏这个特性,在旧的浏览器中,允许声明一个名为undefined的变量,该变量具有一个已定义的值,从而导致测试失败。

#2


11  

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。

#3


4  

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);

#4


2  

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设置为0时,没有定义:

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

在这种情况下,如果getVariable不是一个数字(string, object, whatever), setVariable将被设置为0。

#5


1  

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

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

#6


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.

今天也遇到了这种情况,我不希望为几个值覆盖0。对于这样的场景,我们有一个具有一些常用实用方法的文件。下面是我添加的用于处理场景和灵活的内容。

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是无定义的或null,它会将ID设置为-1,但是不会覆盖0值。

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

#1


251  

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").

是的,它可以这样做,但严格地说,如果检索到的值是falsey,那么它将分配默认值,而不是真正未定义的值。因此,它不仅匹配未定义的,而且还匹配null, false, 0, NaN,“”(但不是“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') ? def_val : x;

On newer browsers it's actually safe to write:

在更新的浏览器上,写:

var x = (x === undefined) ? def_val : 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.

但是要注意的是,在旧的浏览器上有可能破坏这个特性,在旧的浏览器中,允许声明一个名为undefined的变量,该变量具有一个已定义的值,从而导致测试失败。

#2


11  

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。

#3


4  

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);

#4


2  

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设置为0时,没有定义:

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

在这种情况下,如果getVariable不是一个数字(string, object, whatever), setVariable将被设置为0。

#5


1  

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

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

#6


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.

今天也遇到了这种情况,我不希望为几个值覆盖0。对于这样的场景,我们有一个具有一些常用实用方法的文件。下面是我添加的用于处理场景和灵活的内容。

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是无定义的或null,它会将ID设置为-1,但是不会覆盖0值。

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

相关文章