When using javascript, to traverse an array cyclically, there are two commonly used syntaxes:
Copy codeThe Code is as follows:
For (var I; I <array. length; I ++ ){
Statement;
}
For (var I in array ){
Statement;
}
These two methods seem to be able to do the same thing, but in fact the number of cycles of the two cycles is generally different.
The source code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Style>
# Button {text-align: center ;}
# Outer {width: 330px; height: 100px; margin: 10px auto ;}
# Outer div {float: left; width: 100px; height: 100px; margin: 0px 5px; background: black ;}
</Style>
<Script>
Window. onload = function (){
Var obutton = document. getElementsByTagName ("button") [0];
Var outer = document. getElementById ("outer ");
Var outerDiv = outer. getElementsByTagName ("div ");
Obutton. onclick = function (){
For (var p in outerDiv) outerDiv [p]. style. background = "red ";
};
};
</Script>
</Head>
<Body>
<Div id = "button">
<Button> click to Red </button>
</Div>
<Div id = "outer">
<Div> </div>
<Div> </div>
<Div> </div>
</Div>
</Body>
</Html>
This Code uses the for-in statement for loop. It seems that there is no problem.
However, an error is reported during browser debugging:
"Uncaught TypeError: Cannot set property 'background' of undefined"
Why?
If we change the stament content, we will find the problem:
For (var p in outerDiv) alert (p );
Result output: 0 1 2 length item
Therefore, when the property obtains the length and item, it tries to call the style method, of course, undefined. Modify as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Style>
# Button {text-align: center ;}
# Outer {width: 330px; height: 100px; margin: 10px auto ;}
# Outer div {float: left; width: 100px; height: 100px; margin: 0px 5px; background: black ;}
</Style>
<Script>
Window. onload = function (){
Var obutton = document. getElementsByTagName ("button") [0];
Var outer = document. getElementById ("outer ");
Var outerDiv = outer. getElementsByTagName ("div ");
Obutton. onclick = function (){
For (var I = 0; I <outerDiv. length; I ++ ){
OuterDiv [I]. style. background = "red ";
}
};
};
</Script>
</Head>
<Body>
<Div id = "button">
<Button> click to Red </button>
</Div>
<Div id = "outer">
<Div> </div>
<Div> </div>
<Div> </div>
</Div>
</Body>
</Html>