我编写了以下代码:
showTitles = (typeof showTitles !== 'undefined') ? showTitles : 'Y';
showSelectGroup = (typeof showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';
但是 JSLint 说:
警告 3 JS Lint:意外的“typeof”。使用 '===' 直接与 undefined 进行比较。
我应该如何更改我的代码?
我编写了以下代码:
showTitles = (typeof showTitles !== 'undefined') ? showTitles : 'Y';
showSelectGroup = (typeof showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';
但是 JSLint 说:
警告 3 JS Lint:意外的“typeof”。使用 '===' 直接与 undefined 进行比较。
我应该如何更改我的代码?
Probably by using
showTitles = (showTitles === undefined) ? 'Y' : showTitles;
showSelectGroup = (showSelectGroup === undefined) ? 'Y' : showSelectGroup;
jslint has no issues with that (assuming showTitles and showSelectGroup are declared with var)
However, I'd write it as
var showTitles = showTitles || 'Y';
var showSelectGroup = showSelectGroup || 'Y';
Note that whether this is best practice in general is debatable, but if you want to make it work with JSLint, you could do this
showTitles = (showTitles !== undefined) ? showTitles : 'Y';
此消息反映了最新的最佳实践。从 ES5 严格模式开始, 的全局值undefined 不再可以更改,直接比较代码更简单,速度更快。简而言之,JSLint 了解这一切,并为您提供了很好的建议。
在这种情况下,更改typeof showTitles !== 'undefined'为showTitles === undefined。