我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
当前回答
逻辑空赋值,ES2020+解决方案
新的操作符目前正在添加到浏览器中,??=, ||=, &&=。这篇文章将关注??=。
它检查左边是否未定义或为空,如果已经定义,则短路。如果不是,右边的变量被赋值给左边的变量。
比较的方法
// 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文档
其他回答
var setVariable = (typeof localStorage getItem(’value’)! = =’undefined’&& localStorage getItem(’value’))| | 0;
2018年ES6的答案是:
return Object.is(x, undefined) ? y : x;
如果变量x未定义,返回变量y…否则,如果定义了变量x,则返回变量x。
今天也遇到了这种情况,我不想让几个值的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是undefined或null,它会将ID设置为-1,但不会覆盖0值。
data.ID = Util.getIfNotSet(data.ID, -1, true);
检查typeof而不是undefined似乎更合乎逻辑?我假设你期望一个数字,因为你设置var为0时未定义:
var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;
在这种情况下,如果getVariable不是一个数字(字符串、对象等),setVariable将被设置为0
在我们的日子里,你实际上可以用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;