JavaScript中循环遍历Array与Map的方法小结
js循环数组各种方法
eg1:
for(vari=0;i<myStringArray.length;i++){ alert(myStringArray[i]); //Dosomething }
eg2:
Array.prototype.foo="foo!"; vararray=['a','b','c']; for(variinarray){ alert(array[i]); } for(variinthis.$GLOBAL_DETAIL.album_photo_ids){if(this.$GLOBAL_DETAIL.album_photo_ids[i]=="3487675024077108")alert(this.$GLOBAL_DETAIL.album_photo_ids[i]);}
eg3:
[1,2,3,4].map(function(item){ alert(item); })
eg4:
varx=[1,2,3,4].map(function(item){returnitem*10;}); //Andnowxis[10,20,30,40]
eg5:
varmyStringArray=["Hello","World"] varlen=myStringArray.length for(vari=0;i<len;++i){ if(iinmyStringArray){ vars=myStringArray[i]; ...dosomethingwiths... } }
eg6:
varmyStringArray=["Hello","World"] myStringArray.forEach(function(s){ ...dosomethingwiths... })
eg7:
vari=0,item,items=['one','two','three']; while(item=items[i++]){ console.log(item); } //logs:'one','two','three' andforthereverseorder,anevenmoreefficientloop varitems=['one','two','three'],i=items.length; while(i--){ console.log(items[i]); } //logs:'three','two','one' ortheclassicalforloop varitems=['one','two','three'] for(vari=0,l=items.length;i<l;i++){ console.log(items[i]); } //logs:'one','two','three'
eg8:
varmyStringArray=['Hello','World'];//arrayuses[]not{} for(variinmyStringArray){ console.log(i+'->'+myStringArray[i]);//iistheindex/key,nottheitem }
js循环map,获取所有的key和value
eg1:
//Page地址 pageUrl:{ menu:"loadPage.htm?url=/collect/menu.page",//进入菜单页面 guangfaPage:"loadPage.htm?url=/collect/menu.page",//进入广发信息收集页面 pinganPage:"loadPage.htm?url=/collect/menu.page",//进入平安信息收集页面 nuonuoPage:"loadPage.htm?url=/collect/menu.page",//进入诺诺信息收集页面 youbangPage:"loadPage.htm?url=/collect/menu.page",//进入友邦信息收集页面 inputMobileNo:"loadPage.htm?url=/collect/inputMobileNo.page",//进入输入手机号页面 readIdCard:"loadPage.htm?url=/collect/readIdCard.page",//进入读取身份证页面 member:"loadPage.htm?url=/collect/member.page",//进入输入会员卡号页面 bankCard:"loadPage.htm?url=/collect/bankCard.page",//进入插入银行卡页面 url:"loadPage.htm?url=/collect/url.page"//进入跳转url页面 }, for(varkeyinthis.pageUrl){ alert(key+":"+this.pageUrl[key]); }
eg2:
varobj={ "a":1, "b":2, "c":3 }; for(varpropinobj){ if(obj.hasOwnProperty(prop)){ //orif(Object.prototype.hasOwnProperty.call(obj,prop))forsafety... alert("prop:"+prop+"value:"+obj[prop]) } }
双重Map循环
eg:
varmsg=""; for(varkeyinPin){ for(variinPin[key]){ msg+=i+":"+Pin[key][i]+"\n"; } } alert(msg);