0

I'm simply running a function which checks if the variable year is set if not then set it new Date().getFullYear().

The error I get:

Uncaught ReferenceError: year is not defined

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

Why can't I check if year exists and if not set it?

4

2 回答 2

6

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

用于检查函数参数

于 2016-03-22T22:02:23.827 回答
1

您可以使用对象表示法:

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

或者更好地使用typeof

year = (typeof year === "undefined") ? (new Date()).getFullYear() : year
于 2016-03-22T21:53:00.763 回答