admin管理员组

文章数量:1194938

The following code:

var things = {'foo':'bar'}
for ( thing in things ) {
  console.log(thing)
}

Consistently produces the following error in jshint:

Bad for in variable 'thing'.

I do not understand what makes the 'thing' variable 'bad' - as you can see, it is not being used anywhere else. What should I do differently to make jshint not consider this to be an error?

The following code:

var things = {'foo':'bar'}
for ( thing in things ) {
  console.log(thing)
}

Consistently produces the following error in jshint:

Bad for in variable 'thing'.

I do not understand what makes the 'thing' variable 'bad' - as you can see, it is not being used anywhere else. What should I do differently to make jshint not consider this to be an error?

Share Improve this question edited Apr 16, 2014 at 11:21 mikemaccana asked May 2, 2012 at 18:55 mikemaccanamikemaccana 123k110 gold badges427 silver badges529 bronze badges 3
  • 9 It's global, which is always bad (bad bad bad bad bad). Try for( var thing in things). Don't know if this is the reason for the error though :) – Felix Kling Commented May 2, 2012 at 18:57
  • 1 JSHint wants for in variables to be defined in the local scope (i.e. not in an outer function). It's related to this issue: github.com/jshint/jshint/issues/329 – dave1010 Commented Nov 28, 2012 at 9:47
  • 2 Since 'bad' is so vague, I submitted a pull request to jshint so that it explicitly states that the variable is global. – mikemaccana Commented Nov 28, 2012 at 12:04
Add a comment  | 

2 Answers 2

Reset to default 25

They always are - if they are not declared. Try adding var if thing has not been previously declared.

for ( var thing in things ) {
  console.log(thing)
}

or

var thing;

//more code

for ( thing in things ) {
  console.log(thing)
}

Here is your code slightly modified, make sure all is declared before usage.

var things = {'foo':'bar'}, thing;
for ( thing in things ) {
  console.log(thing)
}

本文标签: javascriptJSHint considers a forin variable 39bad39 What does this meanStack Overflow