ped*_*ete 159 javascript undefined
我知道我可以测试一个javascript变量然后定义它,如果它是未定义的,但是没有一些方法可以说
var setVariable = localStorage.getItem('value') || 0;
似乎是一种更清晰的方式,我很确定我已经在其他语言中看到过这种情况.
Aln*_*tak 291
是的,它可以做到这一点,但严格来说,如果检索到的值为false,则会分配默认值,而不是真正的未定义.它将因此不仅符合undefined而且null,false,0,NaN,"" (但没有 "0").
如果你想只在变量是严格的时候设置为默认值,undefined那么最安全的方法是写:
var x = (typeof x === 'undefined') ? def_val : x;
Run Code Online (Sandbox Code Playgroud)
在较新的浏览器上,它实际上是安全的:
var x = (x === undefined) ? def_val : x;
Run Code Online (Sandbox Code Playgroud)
但请注意,可以在允许声明名为undefined具有已定义值的变量的旧版浏览器上进行颠覆,从而导致测试失败.
Gib*_*olt 53
目前正在向浏览器??=、||=、 和 中添加新的运算符&&=。这篇文章将重点放在??=.
这将检查左侧是否为undefined或null,如果已定义则短路。如果不是,则将右侧分配给左侧变量。
// Using ??=
name ??= "Dave"
// Previously, ES2020
name = name ?? "Dave"
// Before that (not equivalent, but commonly used)
name = name || "Dave" // name ||= "Dave"
Run Code Online (Sandbox Code Playgroud)
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
// Equivalent to
a = a ?? true
Run Code Online (Sandbox Code Playgroud)
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" }
Run Code Online (Sandbox Code Playgroud)
??= 浏览器支持2021 年 3 月 - 85%
Ste*_*rne 24
2018年的ES6答案是:
return Object.is(x, undefined) ? y : x;
Run Code Online (Sandbox Code Playgroud)
如果变量x未定义,则返回变量y ...否则,如果定义了变量x,则返回变量x.
wen*_*jun 14
使用Nullish Coalescing Operator,您可以设置默认值(如果value为 null 或未定义)。
const setVariable = localStorage.getItem('value') ?? 0;
Run Code Online (Sandbox Code Playgroud)
但是,您应该知道空合并运算符不会返回其他类型的假值(例如0and )的默认值''。
但是,请注意浏览器支持。您可能需要使用像Babel这样的 JavaScript 编译器将其转换为更向后兼容的内容。如果您使用的是 Node.js,则从版本 14开始就支持它。
检查似乎更合乎逻辑typeof而不是undefined?我假设您期望一个数字,因为您0在未定义时将var设置为:
var getVariable = localStorage.getItem('value');
var setVariable = (typeof getVariable == 'number') ? getVariable : 0;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果getVariable不是数字(字符串,对象,等等),则setVariable设置为0
我需要在几个地方"设置一个未定义的变量".我使用@Alnitak答案创建了一个函数.希望它可以帮助某人.
function setDefaultVal(value, defaultValue){
return (value === undefined) ? defaultValue : value;
}
Run Code Online (Sandbox Code Playgroud)
用法:
hasPoints = setDefaultVal(this.hasPoints, true);
Run Code Online (Sandbox Code Playgroud)
在我们的日子里,你实际上可以用 JS 来做你的方法:
// Your variable is null
// or '', 0, false, undefined
let x = null;
// Set default value
x = x || 'default value';
console.log(x); // default value
Run Code Online (Sandbox Code Playgroud)
所以你的例子将起作用:
const setVariable = localStorage.getItem('value') || 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177002 次 |
| 最近记录: |