JavaScript循環(huán)遍歷小結(jié)
總結(jié)JavaScript中的循環(huán)遍歷
定義一個(gè)數(shù)組和對(duì)象
const arr = ['a', 'b', 'c', 'd', 'e', 'f']; const obj = { a: 1, b: 2, c: 3, d: 4 }
for()
經(jīng)常用來(lái)遍歷數(shù)組元素
遍歷值為數(shù)組元素索引
for (let i = 0; len = arr.length, i < len; i++) { console.log(i); // 0 1 2 3 4 5 console.log(arr[i]); // a b c d e f }
forEach()
用來(lái)遍歷數(shù)組元素
第一個(gè)參數(shù)為數(shù)組元素,第二個(gè)參數(shù)為數(shù)組元素索引,第三個(gè)參數(shù)為數(shù)組本身(可選)
沒(méi)有返回值
arr.forEach((item, index) => { console.log(item); // a b c d e f console.log(index); // 0 1 2 3 4 5 })
map()
用來(lái)遍歷數(shù)組元素
第一個(gè)參數(shù)為數(shù)組元素,第二個(gè)參數(shù)為數(shù)組元素索引,第三個(gè)參數(shù)為數(shù)組本身(可選)
有返回值,返回一個(gè)新數(shù)組
every(),some(),filter(),reduce(),reduceRight()不再一一介紹,詳細(xì)請(qǐng)看Js中Array方法有哪些? let arrData = arr.map((item, index) => { console.log(item); // a b c d e f console.log(index); // 0 1 2 3 4 5 return item; }) console.log(arrData); // ["a", "b", "c", "d", "e", "f"]
for...in
可循環(huán)對(duì)象和數(shù)組,推薦用于循環(huán)對(duì)象
用于循環(huán)對(duì)象時(shí)
循環(huán)值為對(duì)象屬性
for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(key); // a b c d 屬性 console.log(obj[key]); // 1 2 3 4 屬性值 } }
用于遍歷數(shù)組時(shí)
值為數(shù)組索引
for (let index in arr) { console.log(index); // 0 1 2 3 4 5 數(shù)組索引 console.log(arr[index]); // a b c d e f 數(shù)組值 }
當(dāng)我們給數(shù)組添加一個(gè)屬性name
arr.name = '我是自定義的屬性'
for (let index in arr) { console.log(index); // 0 1 2 3 4 5 name (會(huì)遍歷出我們自定義的屬性) console.log(arr[index]); // a b c d e f 我是自定義屬性name }
for...of
可循環(huán)對(duì)象和數(shù)組,推薦用于遍歷數(shù)組
用于遍歷數(shù)組時(shí)
遍歷值為數(shù)組元素
for (let value of arr) { console.log(value); // a b c d e f 數(shù)組值 }
用于循環(huán)對(duì)象時(shí)
須配合Object.keys()一起使用,直接用于循環(huán)對(duì)象會(huì)報(bào)錯(cuò),不推薦使用for...of循環(huán)對(duì)象
循環(huán)值為對(duì)象屬性
for (let value of Object.keys(obj)) { console.log(value); // a b c d 對(duì)象屬性 }
總結(jié)
用于遍歷數(shù)組元素使用:for(),forEach(),map(),for...of
用于循環(huán)對(duì)象屬性使用:for...in
以上所述是小編給大家介紹的JavaScript循環(huán)遍歷你會(huì)用哪些小結(jié)篇,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
JS清除文本框內(nèi)容離開(kāi)在恢復(fù)及鼠標(biāo)離開(kāi)文本框時(shí)觸發(fā)js的方法
多網(wǎng)站的需要填寫(xiě)的文本框在默認(rèn)狀態(tài)下都會(huì)給出一個(gè)默認(rèn)的提示語(yǔ)言,當(dāng)鼠標(biāo)點(diǎn)擊此文本框的時(shí)候能夠?qū)⒗锩娴哪J(rèn)文本清除,當(dāng)刪除輸入的文本且焦點(diǎn)離開(kāi)文本框的時(shí)候再將默認(rèn)的文本寫(xiě)入文本框2016-01-01使用Mock.js生成前端測(cè)試數(shù)據(jù)
這篇文章主要介紹了使用Mock.js生成前端測(cè)試數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12javascript dom 操作詳解 js加強(qiáng)
javascript dom 操作詳解 js加強(qiáng)操作實(shí)現(xiàn)代碼。2009-07-07JavaScript實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的方式匯總
這篇文章主要介紹了JavaScript實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的方式匯總的相關(guān)資料,需要的朋友可以參考下2016-05-05