for循环、for-in、forEach、for-of

2017-06-15  本文已影响0人  Aoyi_G
  1. 要遍历数组,最简单的方式即for循环:
var a = [1,2,3],
len =a.length;
for(var i=0 ; i < len ; i++){
console.log(a[i]);
}

这样的方式是最简单直接的方法,但是这样的方式需要的变量比较多

  1. 在ES5之后,我们可以使用forEach进行数组遍历,这种方法更加简洁,但是不能使用breack语句中断循环,也不能使用return语句返回到外层函数。
var a = [1,2,3],
len =a.length;
a.forEach(function(el,index){
  console.log(index +":"+el);
});
//0:1
//1:2
//2:3
  1. for-in是另一种方式,但是有几个缺点:
for (var index in a) { // 千万别这样做
  console.log(a[index]);
}
  1. 强大的for-of循环,是ES6的新语法。
for (var value of myArray) {
  console.log(value);
}

总之,for-in循环用来遍历对象属性;for-of循环用来遍历数据—例如数组中的值。for-of循环不仅支持数组,还支持大多数类数组对象,例如DOM [NodeList对象]。for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:

for (var chr of "ab") {
  console.log(chr);
}
//a
//b
上一篇 下一篇

猜你喜欢

热点阅读