這篇文章給大家分享的是有關(guān)JavaScript如何實(shí)現(xiàn)循環(huán)遍歷的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
總結(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)常用來遍歷數(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()
用來遍歷數(shù)組元素
第一個(gè)參數(shù)為數(shù)組元素,第二個(gè)參數(shù)為數(shù)組元素索引,第三個(gè)參數(shù)為數(shù)組本身(可選)
沒有返回值
arr.forEach((item, index) => { console.log(item); // a b c d e f console.log(index); // 0 1 2 3 4 5 })
map()
用來遍歷數(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ì)象屬性 }
感謝各位的閱讀!關(guān)于“JavaScript如何實(shí)現(xiàn)循環(huán)遍歷”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
本文題目:JavaScript如何實(shí)現(xiàn)循環(huán)遍歷-創(chuàng)新互聯(lián)
標(biāo)題來源:http://aaarwkj.com/article20/ihsjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、網(wǎng)站導(dǎo)航、微信小程序、定制網(wǎng)站、云服務(wù)器、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容