Home >Web Front-end >JS Tutorial >How to use loop in js?
1. for loop
Four steps:
1. Set the initial value var i = 0
2. Set the loop execution condition i
3. Execute the content in the loop body {[loop body]} wrapped part
4. After each round of loop, our i++ accumulation operation is executed
for(var i = 0;i
break/continue: in the loop When these two keywords are encountered in the body, the subsequent code in the loop body will no longer be executed
Break: In the loop body, if break appears, the entire loop will end directly , the last cumulative operation of i++ is not executed either
Continue: In the loop body, if continue appears, the current round of the loop ends and the next round of loop continues. , i++ continues to execute
for(var i = 0;i
2. for in loop
Used to loop a
object ='小李'18'170cm''敲代码'
for(var key in object){
console.log(key);// The attribute name obtained in each loop
Console.log(object[key])// Obtaining the attribute value in for in can only be obtained through the object name[key] and cannot write obj.key
}
Case: changing the color of every other row in the table (the ternary operator satisfies the condition and if there are multiple executions, you can add parentheses and separate them with commas)
nbsp;html> <meta> <title>Document</title> <style>body,div,ul,li{ margin:0; padding: 0; font-family: Arial; font-size:12px; } ul li{ list-style:none; } #list{ margin:10px auto 0; padding:10px; width:500px; border:1px solid #ddd; border-radius:10px;/*background: -webkit-linear-gradient(top left,#31b0d5,#67b168,#ac2925)*/} #list li{ height:30px; line-height: 30px; cursor:pointer; } .c1{ background:#ddd; } .c2{ background: #a6e1ec; } .c3{ background: #67b168; }</style> <div> <ul> <li>11111111111111111111111111</li> <li>22222222222222222222222222</li> <li>33333333333333333333333333</li> <li>44444444444444444444444444</li> <li>55555555555555555555555555</li> <li>66666666666666666666666666</li> <li>11111111111111111111111111</li> <li>22222222222222222222222222</li> <li>33333333333333333333333333</li> <li>44444444444444444444444444</li> <li>55555555555555555555555555</li> <li>66666666666666666666666666</li> </ul> </div> <script>//原理:操作所有的li,让按照奇偶行的规律,改变他的class样式的属性值,奇数行是c1,偶数行是c2//通过元素的标签名获取一组元素// document.getElementsByTagName('元素的标签名字')//在整个文档中(获取的范围,上下文),我们通过元素的标签名来获取一组元素//获取整个文档的所有的li,他是一个集合,我们把这个集合叫做类数组(类似于数组)//并且类数组是对象数据类型的// var oLis = document.getElementsByTagName('li');//索引:就是代表当前是第几个元素的位置下标,索引是从0开始的//length:代表获取的集合的长度,或者是当前获取了多少li//通过dom方法获取到的类数组可以通过用.item(索引)来获取某一个var oList = document.getElementById('list');var oLis = oList.getElementsByTagName('li');for(var i = 0;i<oLis.length;i++){var oLi = oLis[i]; i%2===0?oLi.className = 'c1':oLi.className='c2'}</script>
The above is the detailed content of How to use loop in js?. For more information, please follow other related articles on the PHP Chinese website!