如果未定义,javascript设置变量

时间:2011-03-23 18:06:57

标签: javascript undefined

我知道我可以测试一个javascript变量,然后定义它是否未定义,但是没有某种说法

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

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

13 个答案:

答案 0 :(得分:282)

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

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

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

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

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

但请注意,可以在较旧的浏览器上对此进行破坏,允许声明名为undefined且具有已定义值的变量,从而导致测试失败。

答案 1 :(得分:22)

2018年的ES6答案是

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

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

答案 2 :(得分:10)

逻辑无效分配,ES2020 +解决方案

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

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

比较方法

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

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

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

基本示例

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

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

// Equivalent to
a = a ?? true

对象/数组示例

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 2020年11月-77%

??= Mozilla Documentation

||= Mozilla Documentation

&&= Mozilla Documentation

答案 3 :(得分:8)

ES2020答案

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

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

但是,您应该注意,空值合并运算符不会为其他类型的伪造值(例如0'')返回默认值。

请注意,浏览器对操作员的支持是有限的。根据{{​​3}}的数据,截至2020年4月,仅支持48.34%的浏览器。 Node.js支持为caniuse

答案 4 :(得分:6)

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

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

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

答案 5 :(得分:5)

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

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

用法:

hasPoints = setDefaultVal(this.hasPoints, true);

答案 6 :(得分:3)

在当今时代,您实际上可以使用JS进行处理:

<h1>Hunger Games Tribute Status:</h1>
<button onclick="startgame()">START GAME</button>
<h5 id="hunger"></h5>

因此您的示例将起作用:

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

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

console.log(x); // default value

答案 7 :(得分:1)

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

答案 8 :(得分: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;
    }
}

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

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

答案 9 :(得分:0)

如果您是FP粉丝,Ramda为此提供了一个简洁的辅助功能,称为defaultTo

用法:

Length / 2

在处理 DataPart1.data = Encoding.ASCII.GetString(dataByte.Take(dataByte.Length / 2).ToArray()); DataPart2.data = Encoding.ASCII.GetString(dataByte.Skip(DataPart1.data.Count()).ToArray()).ToString(); 布尔值时更有用:

const result = defaultTo(30)(value)

答案 10 :(得分:0)

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

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

答案 11 :(得分:0)

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

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

是执行此操作的一种好方法(使用对象解构)。

答案 12 :(得分:0)

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

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

在 ES12 或之后

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