forEach
forEach是js中遍歷數(shù)組的方法
var a=[1,2,3,4];
a.forEach(function(elem,index){
console.log(index+" "+elem)
})
forEach有3個(gè)參數(shù)换淆,第一個(gè)參數(shù)表示遍歷的數(shù)組內(nèi)容地技,第二個(gè)參數(shù)是數(shù)組的索引朗鸠,第三個(gè)參數(shù)是數(shù)組本身。一般寫(xiě)前兩個(gè)參數(shù),第三個(gè)參數(shù)省略,在IE9前面的版本是不支持的咽弦,而且不能中斷循環(huán)
$.each()
是jQuery中的方法
var a=[1,2,3,4];
$.each(a,function(index,elem){
console.log(index+' '+elem)
})
each的前兩個(gè)參數(shù)和forEach相反
$.fn.each()
遍歷元素
$('li').each(function(i,v){
console.log(i);//索引
console.log(v);//元素
})
map
說(shuō)到forEach徒蟆,順便提一下map,map用法類(lèi)似于forEach型型,這里的map表示映射
a.map(function(value,index,array){
console.log(index+" "+value)
})
常用于:在一個(gè)數(shù)組段审,數(shù)組中元素為對(duì)象的狀況
數(shù)組對(duì)象
如果想在每個(gè)對(duì)象中添加一個(gè)show:true,這樣的鍵值對(duì)闹蒜,使用map方法
image.png
如果不想要原對(duì)象中的鍵值對(duì)寺枉,去掉...item.
for -- of遍歷Set對(duì)象
var a=new Set([1,1,2,2,3,4,4,6])
for(let i of a){
console.log(i);
}