14

我编写了以下代码:

showTitles = (typeof showTitles !== 'undefined') ? showTitles : 'Y';
showSelectGroup = (typeof showSelectGroup !== 'undefined') ? showSelectGroup : 'Y';

但是 JSLint 说:

警告 3 JS Lint:意外的“typeof”。使用 '===' 直接与 undefined 进行比较。

我应该如何更改我的代码?

4

3 回答 3

9

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';
于 2012-09-27T18:45:36.597 回答
8

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';
于 2012-09-27T18:45:54.070 回答
7

此消息反映了最新的最佳实践。从 ES5 严格模式开始, 的全局值undefined 不再可以更改,直接比较代码更简单,速度更快。简而言之,JSLint 了解这一切,并为您提供了很好的建议。

在这种情况下,更改typeof showTitles !== 'undefined'showTitles === undefined

于 2015-12-01T03:22:35.033 回答