JavaScript里的循环方法:forEach,for-in,for-of,each

1、常用的for循环

for (var index = 0; index < myArray.length; index++) {
  console.log(myArray[index]);
}

2、forEach
自从JavaScript5起,我们开始可以使用内置的forEach方法:

arr.forEach((item,index,arr)=>{
  //doSomthing
                    })

写法简单了许多,但也有短处:你不能中断循环(使用break语句或使用return语句。forEach方法是用来遍历数组和json对象的
3、for-in
for-in循环实际是为循环”enumerable“对象而设计的:(不建议用作数组)

var obj = {a:1, b:2, c:3};
for (var prop in obj) {
  console.log(prop);
}
//a
//b
//c

4、for-of
JavaScript6里引入了一种新的循环方法,它就是for-of循环,它既比传统的for循环简洁,同时弥补了forEach和for-in循环的短板。
可以循环一个数组Array、字符串、类型化的数组(TypedArray)、Map、Set、 DOM collection:

5、each

each是专用来遍历jquery对象的,如$("li")可以获取到包含多个li标签的对象,这是我们如果想要给每个li加上相同的事件

这时我们就需要用each方法来实现;

$('li').each(function(){
                alert($(this).text())
              })

你可能感兴趣的:(JavaScript里的循环方法:forEach,for-in,for-of,each)