for (var i = 0; child && i < child.length; i++) { var obj = child[i]; var kind = child[i].kind; var deiveId = child[i].id; if (kind == "4") {//分支1 // do sometjing }else{//分支2 for(i in arr){ //do something } }
The above code creates a problem that seems very strange on the surface, that is, if kind! In the case of branch 2 of =4, sometimes the outer for loop will turn back, that is: the outermost layer has obviously looped to the last child. After running branch 2, the outer for loop Go back and execute again.
Cause analysis:
I think if professionals are not as bad as me, they will find that the problem lies in variablei, where i will not become block level Variables, but functionlevel. Changes in i in branch 2 will cause changes in outer i, causing the loop to return.
js did not have block-level scope before ES6, and was only divided into global scope and function-level scope. Here i is the function-level scope, and when we use it to do loops index, in fact It is intended to be used as a block-level scope.
Solution
If you want to achieve the block-level scope effect, you can use the let keyword of ES6 syntax to achieve it:
for(let i=0;i<arr.length;i++){ }
I believe I read the case in this article You have mastered the method. For more exciting information, please pay attention to php Chinese website Other related articles!
Recommended reading:
Summary of commonly used css styles
Detailed explanation of the difference between Component and PureComponent
The above is the detailed content of Bugs encountered when using js variable scope. For more information, please follow other related articles on the PHP Chinese website!