首页 > 代码库 > 使用for in循环遍历json对象的数据
使用for in循环遍历json对象的数据
使用for in遍历json对象数据,如果数据中的名称有为数字的话,只对正整数有效,那么先会输出为正整数的数据,后面其他的会按照原来数据中定义的顺序不变输出。
- 针对名称为数字的json对象数据进行测试,代码如下:
<script type="text/javascript"> var json_obj_data =http://www.mamicode.com/ { "40":{"title":"all" , "name" :"all promotions" ,"id" :"all"}, "20":{"title":"best_room_rate" , "name" : "best room rate" , "id" : "best_room_rate"}, "10":{"title":"summer rate" , "name" : "summer rate" , "id" : "30"} }
//40,20,10可以不加双引号括住,输出的结果是一样的for(var data in json_obj_data){ alert(data);//10->20->40 }</script>
- 针对名称为字符串的json对象数据进行测试,代码如下:
var json_data = http://www.mamicode.com/{"3promotion":{"title":"all","room_promotion_id":"all"}, "2promotion":{"title":"best_room_rate","roompromotion_id":"best_room_rate"}, "1promotion":{"title":"Summer Room rate" , "room_promotion_id":"30"} }; for(var promotion in json_data){ alert(promotion);//输出结果是按照上面定义的顺序}
- 针对名称为数字和字符串的json对象数据测试,代码如下:
var json_data = http://www.mamicode.com/{"3promotion":{"title":"all","room_promotion_id":"all"}, "2promotion":{"title":"best_room_rate","roompromotion_id":"best_room_rate"}, "1":{"title":"Summer Room rate" , "room_promotion_id":"30"} }; for(var promotion in json_data){ alert(promotion);//数据先输出的是名称为数字的,然后就按照顺序输出名称为字符串的 }
具有两个名称为数字的,其他为字符串的json对象数据测试,代码如下:
var json_data = http://www.mamicode.com/{"3promotion":{"title":"all","room_promotion_id":"all"}, "2promotion":{"title":"best_room_rate","roompromotion_id":"best_room_rate"}, "1":{"title":"Summer Room rate" , "room_promotion_id":"30"}, "0":{"title":"expecial rate" , "room_promotion_id":"60"} }; for(var promotion in json_data){ alert(promotion);//输出结果为0->1->3promotion->2promotion}
具有名称为数字,其中有为负数的将会被当作字符串处理,其他为字符串的json对象数据测试,代码如下:
var json_data = http://www.mamicode.com/{"3promotion":{"title":"all","room_promotion_id":"all"}, "2promotion":{"title":"best_room_rate","roompromotion_id":"best_room_rate"}, "1":{"title":"Summer Room rate" , "room_promotion_id":"30"}, "0":{"title":"expecial rate" , "room_promotion_id":"60"}, "-1":{"title":‘demo3‘,‘room_promotion_id‘:"demo3"} }; for(var promotion in json_data){ alert(promotion);//0->1->3promotion->2promotion->-1 }
包括小于1的数字名称,以及数字为负数的名称,代码测试如下:
var json_data = http://www.mamicode.com/{"3promotion":{"title":"all","room_promotion_id":"all"}, "2promotion":{"title":"best_room_rate","roompromotion_id":"best_room_rate"}, "1":{"title":"Summer Room rate" , "room_promotion_id":"30"}, "0.25":{"title":"expecial rate" , "room_promotion_id":"60"}, "-1":{"title":‘demo3‘,‘room_promotion_id‘:"demo3"} }; for(var promotion in json_data){ alert(promotion);//1->3promotion->2promotion->0.25->-1
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。