一、js实现遍历对象
<script>
var obj = {"player_id":"GS001","event_id":"","destroy":"97%"};
var props = "";
for(var p in obj){
if(typeof(obj[p])=="function"){
obj[p](); 执行方法
}else{
props+= p + "=" + obj[p] + " "; 输出属性
}
}
alert(props);
</script>
遍历数组
<script type="text/javascript">
//比如
var values=["北京","天津"];
//遍历1 for(var i=;i<values.length;i++){ 只能用于数组 因为对象没有长度值
alert(values[i]);
} //遍历2 for(var ele in values){
alert(values[ele]);//下标 } </script>
二、JQuery遍历
遍历数组
$(function(){
//------------遍历数组 .each的使用-------------
var anArray = ['one','two','three'];
$.each(anArray,function(n,value) {
alert(n+' '+value);
trs += "<tr><td>" +value+"</td></tr>";
}); });
遍历对象
$(function(){
//------------遍历对象 .each的使用-------------
//对象语法JSON数据格式(当服务器端回调回来的对象数据格式是json数据格式,必须保证JSON的格式要求,回调的对象必须使用eval函数进行转化(否则将得不到Object)。本文不作详细介绍服务器端回调的数据问题,我们将直接自定义对象)
var obj =[{"name":"admin","password":""}];
//下面使用each进行遍历
$.each(obj,function(n,value) {
alert(n+' '+value);
trs += "<tr><td>" + value.name +"</td> <td>" + value.password +"</td></tr>";
}); });
多为数组遍历
<script>
$(function(){
var summ={"errno":,"errstr":"","content":[{"city":"52","region_name":"\u5317\u4eac"},{"city":"138","region_name":"\u77f3\u5bb6\u5e84"},{"city":"180","region_name":"\u6b66\u6c49"},{"city":"197","region_name":"\u957f\u6c99"},{"city":"343","region_name":"\u5929\u6d25"}]};
$.each(summ,function(v,value){
if (typeof value=="object") {
$.each(value,function(vv,values){
alert(values.region_name);
}) }else{
alert(value);
}; })
})
</script>
for(k in arr){} 实现
<script>
var summ={"errno":,"errstr":"","content":[{"city":"","region_name":"\u5317\u4eac"},{"city":"","region_name":"\u77f3\u5bb6\u5e84"},{"city":"","region_name":"\u6b66\u6c49"},{"city":"","region_name":"\u957f\u6c99"},{"city":"","region_name":"\u5929\u6d25"}]}; for (var k in summ) {
if (typeof summ[k]=="object") {
for (var n in summ[k]) {
alert(summ[k][n].city);
alert(summ[k][n].region_name);
};
}else{
alert(summ[k]);
}; };
</script>