我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
我知道我可以测试一个JavaScript变量,然后定义它,如果它是未定义的,但有没有某种方式说
var setVariable = localStorage.getItem('value') || 0;
这似乎是一种更清晰的方式,我很确定我在其他语言中见过这种情况。
当前回答
检查typeof而不是undefined似乎更合乎逻辑?我假设你期望一个数字,因为你设置var为0时未定义:
var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;
在这种情况下,如果getVariable不是一个数字(字符串、对象等),setVariable将被设置为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;
是的,它可以这样做,但严格来说,如果检索到的值是假的,将分配默认值,而不是真正未定义的。因此,它不仅可以匹配undefined,还可以匹配null, false, 0, NaN, ""(但不匹配"0")。
如果你只想在变量严格未定义的情况下设置为默认值,那么最安全的方法是这样写:
var x = (typeof x === 'undefined') ? your_default_value : x;
在新的浏览器上,这样写其实是安全的:
var x = (x === undefined) ? your_default_value : x;
但是请注意,在旧的浏览器中,允许声明一个名为undefined的变量,该变量具有一个已定义的值,这可能会导致测试失败。
在我们的日子里,你实际上可以用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;
2018年ES6的答案是:
return Object.is(x, undefined) ? y : x;
如果变量x未定义,返回变量y…否则,如果定义了变量x,则返回变量x。