Home > Web Front-end > JS Tutorial > body text

Bugs encountered when using js variable scope

php中世界最好的语言
Release: 2018-05-24 15:57:13
Original
1812 people have browsed it
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
                }
            }
Copy after login

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++){
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template