溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript如何實(shí)現(xiàn)循環(huán)遍歷

發(fā)布時(shí)間:2021-07-24 14:33:25 來(lái)源:億速云 閱讀:120 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)JavaScript如何實(shí)現(xiàn)循環(huán)遍歷的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

總結(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ì)象屬性
}

感謝各位的閱讀!關(guān)于“JavaScript如何實(shí)現(xiàn)循環(huán)遍歷”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI