js中的遍历foreach,$.each(),$().each()
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title></title>
</head>
<body>
<h3>1</h3>
<h3>2</h3>
<h3>3</h3>
<div id='in'></div>
<div id='each'></div>
<div id='in2'></div>
<div id='each2'></div>
<span id='span1'></span>
<span id='span2'></span>
<span id='span3'></span>
</body>
<script src="jquery-2.1.1.js"></script>
<script type="text/javascript">
var array = ['v1','v2','v3'];
var obj = {'length':10,'width':5};
var jqueryobj = $('h3');
//遍历对象
for(var key in obj){//js中没有foreach关键字,只不过是通过for in来实现
$('#in').append(key+':'+obj[key]+'<br>');
}
$.each(obj,function(key,value){//此方法可用于例遍任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。
$('#each').append(key+':'+value+'<br>');
});
//遍历数组
for(var key in array){
$('#in2').append(key+':'+array[key]+'<br>');
}
$.each(array,function(key,value){
$('#each2').append(key+':'+value+'<br>');
});
//遍历jQuery对象
$.each(jqueryobj,function(index){
$('#span2').append(index+":"+$(this).text()+'<br>');
});
jqueryobj.each(function(index){//此方法只能遍历jQuery对象
$('#span3').append(index+":"+$(this).text()+'<br>');
});
</script>
</html>
结果:
1
2
3
length:10
width:5
length:10
width:5
0:v1
1:v2
2:v3
0:v1
1:v2
2:v3
0:1
1:2
2:3
0:1
1:2
2:3