for 循环代码块必定的次数,它有三个参数,来决定代码块的循环次数,第一个是初始值,第二个是终止值,第三个参数是变化规则:javascript
//for循环 for(var i = 0, len = jsonArr.length; i < len; i++) { console.log(JSON.stringify(jsonArr[i])); }
for in循环通常用于遍历对象的属性,它有两个参数,in以前为属性名参数,in以后为要遍历的对象,它会遍历对象中的每个属性,key即为属性名,对象【属性名】则输出属性值:java
for(var key in jsonObj) { console.log(key + ':' + jsonObj[key]); }
注意:这里的key是字符串,而不是真正的索引,for in是为普通对象设计的循环,能够遍历获得字符串类型的键,若是用它来遍历数组则不方便。node
forEach循环json
jsonArr.forEach(function(value,index,array){ console.log('********************'); console.log(value); console.log(index); console.log(array); });
这是输出结果,能够看到,value是数组元素值,index为当前值得索引,array则为当前所遍历的数组对象。数组
for of循环dom
var jsonArr = [{ 'one': '1' }, { 'two': '2' }, { 'three': '3' } ]; //for of循环 for(var value of jsonArr) { console.log(value); }
将输出数组的每一项的值。测试
for-of循环除了能够遍历数组,也能够遍历其它的集合。好比,大多数类数组对象,例如DOM NodeList对象。设计
var nodeLis = document.getElementById('ul').childNodes; //for of循环 for(var value of nodeLis) { console.log(value); }
for-of循环也支持字符串遍历,它将字符串视为一系列的Unicode字符来进行遍历:3d
var str = 'i am little sun'; for(var value of str) { console.log(value); }
while和do while循环:code
var i=0 while(i<5){ console.log(i); i++; } do{ console.log(i); i++; }while(i<5)
两者的区别是,do while不管条件知足与否都会至少执行一次。
$.each()用于遍历数组和对象:
遍历数组:
var arr1 = [0, 1, 2, 3, 4]; var arr2 = $('ul li'); $.each(arr1, function(index,value) { console.log(index) console.log(value) });
遍历对象:
$.each(jsonObj, function(key, val) { alert(jsonObj[key]); });
$().each()用于遍历jQuery中的节点对象:$(selector).each(function(index,element))
$( $('ul li')).each(function(index,value){ console.log(index) console.log(value) });
部分文章中有提到,$.().each()主要用于处理dom,在测试中发现其实二者均可以一样的用于处理dom,彷佛没有什么大的区别。