简写 if/else 变量存在

shorthand if/else variable exists

本文关键字:变量 存在 else if 简写      更新时间:2023-09-26

我只是在运行一个函数,该函数检查变量year是否已设置,如果没有,则将其设置为new Date().getFullYear()

我得到的错误:

捕获的引用错误:未定义年份

year = (year) ? year : new Date().getFullYear();
console.log(year);

为什么我无法检查year是否存在,如果没有设置它?

year = year || new Date().getFullYear();

有助于检查函数参数

year = year ?? new Date().getFullYear();

另一种方式

您可以使用对象表示法:

// In the global scope window is this
this['year'] = this['year'] ? year : (new Date).getFullYear();
console.log(year);

或者也许更好地使用类型类型

year = (typeof year === "undefined") ? (new Date()).getFullYear() : year