咱們把idx和obj都打印出來看看,究竟是什麼東西json
var json1 =[{"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json1, function(idx, obj) { console.log(idx); console.log(obj); console.log(obj.tagName); });
控制檯截圖數組
咱們能看到,idx是索引,obj是對象,tagName能夠經過obj直接拿到app
var json2 = {"list":[ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ],"total":5}; $.each(json2,function(index,element){ console.log("index:"+index); console.log("element:"+element); $.each(element,function(name,value){ console.log("name:"+name); console.log("value:"+value); console.log("value.tagName:"+value.tagName); }) });
在這裏咱們用多層嵌套來實現,而不能用單層循環,經過element.list[i].tagName,element.list[0].tagName等等,任未嘗試都是徒勞的spa
必需要從Object裏面拿,xx.xx格式纔是正確,xx.xx.xx或者xx.xx.xx.xx,固然JavaScript的for循環卻能夠這麼取數據。code
接下來咱們看看打印出來什麼東西對象
很清晰的看出,index打印出了外層的list和total,即爲索引;element打印出list的五個對象,因此沒法單層拿出tagName,最後一個element打印出了total的值blog
name是對象的索引,內層把value循環遍歷出來,咱們能看到一個對象,總共五個,而後經過這一個對象拿出其tagName的值索引
JavaScript的for遍歷二層jsonip
for (var i=0;i<json2.list.length;i++){ alert(i + json2.list[i].tagName); }
我的感受,原生的簡潔易懂element