質問

I use code like the below in javascript. Is it wrong?

for(i=0;i<5;i++){

function somefunction(){
/*function code here*/
}

somefunction();//call that function inside the loop
}//end of for loop

I think i wrote a code using this and i messed up everything.

役に立ちましたか?

解決

Functions and variables in JavaScript are scoped to the nearest function, not the nearest block ({ ... }).

So you cannot define different functions or variables each time around the loop, because you are overwriting the same name in the same scope.

As such, it would be a bad idea to put such a declaration inside the loop, whether or not the standards or implementations allowed you to do so, because it would serve only to mislead anyone reading the code (most likely yourself!).

You can create an anonymous function inside the loop, but without more context, I can't really give an example of how that would help you.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top