j-3. foreach ,for of ,for in-------待续

each()是jquery中的

each() 方法规定为每个匹配元素规定运行的函数。

提示:返回 false 可用于及早停止循环。

$(selector).each(function(index,element))

.each()是一个for循环的包装迭代器
.each()通过回调的方式处理,并且会有2个固定的实参,索引与元素(从0开始计数)
.each()回调方法中的this指向当前迭代的dom元素

<button class="click">回调判断</button>
<script type="text/javascript">
    $(".click").click(function() {
        $("li").each(function(index, element) { //遍历所有的li
            if (index % 2) {  //修改偶数li内的字体颜色
                $(this).css('color','blue')
            }
        })
    })
</script>

for in

for in 遍历的实际是对象的属性名称也就是索引

index 索引为字符串,无法直接进行几何运算

遍历出来按照索引值大小排列打乱以前排序

所以一般只有不用它



a.name = "Hello";
for(x in a){
  console.log(x); //0,1,2,name
}

 
arr={3:6,1:4,2:5};
//   a.name = "Hello";
for(let index in arr){
  console.log(index,arr[index]); //1:4,2:5,3:6
}

for of (es6新特性)

它遍历的是素组内的元素

var array = [1,2,3,4,5,6,7];

for(let v of array) {
    console.log(v);
};

结果如下:
1
2
3
4
5
6
7

forEach()

array=[1,2,3,4,5,6]
array.forEach(v=>{
    console.log(v);
});
 
结果:1 2 3 4 5 6
原文地址:https://www.cnblogs.com/stone5/p/9062797.html