简体   繁体   English

if/else 变量存在的简写

[英]shorthand if/else variable exists

I'm simply running a function which checks if the variable year is set if not then set it new Date().getFullYear() .我只是运行一个函数来检查变量year是否设置,如果没有设置它new Date().getFullYear()

The error I get:我得到的错误:

Uncaught ReferenceError: year is not defined未捕获的 ReferenceError:未定义年份

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

Why can't I check if year exists and if not set it?为什么我不能检查year是否存在,如果没有设置?

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

用于检查函数参数

You can use Object Notation:您可以使用对象表示法:

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

or perhaps better use typeof或者更好地使用typeof

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

另一种方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM