国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

JavaScript循環遍歷你會用哪些之小結篇

2024-05-06 15:29:21
字體:
來源:轉載
供稿:網友

總結JavaScript中的循環遍歷

定義一個數組和對象

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];const obj = {  a: 1,  b: 2,  c: 3,  d: 4}

for()

經常用來遍歷數組元素

遍歷值為數組元素索引

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()

用來遍歷數組元素

第一個參數為數組元素,第二個參數為數組元素索引,第三個參數為數組本身(可選)

沒有返回值

arr.forEach((item, index) => {  console.log(item);   // a b c d e f   console.log(index);  // 0 1 2 3 4 5})

map()

用來遍歷數組元素

第一個參數為數組元素,第二個參數為數組元素索引,第三個參數為數組本身(可選)

有返回值,返回一個新數組

every(),some(),filter(),reduce(),reduceRight()不再一一介紹,詳細請看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

可循環對象和數組,推薦用于循環對象

用于循環對象時

循環值為對象屬性

for (let key in obj) {  if (obj.hasOwnProperty(key)) {    console.log(key);      // a b c d 屬性    console.log(obj[key]);  // 1 2 3 4 屬性值  }}

用于遍歷數組時

值為數組索引

for (let index in arr) {  console.log(index);     // 0 1 2 3 4 5 數組索引  console.log(arr[index]);  // a b c d e f 數組值}

當我們給數組添加一個屬性name

arr.name = '我是自定義的屬性'

for (let index in arr) {  console.log(index);      // 0 1 2 3 4 5 name (會遍歷出我們自定義的屬性)  console.log(arr[index]);  // a b c d e f 我是自定義屬性name}

for...of

可循環對象和數組,推薦用于遍歷數組

用于遍歷數組時

遍歷值為數組元素

for (let value of arr) {  console.log(value);    // a b c d e f 數組值}

用于循環對象時

須配合Object.keys()一起使用,直接用于循環對象會報錯,不推薦使用for...of循環對象

循環值為對象屬性

for (let value of Object.keys(obj)) {  console.log(value);  // a b c d 對象屬性}

總結

用于遍歷數組元素使用:for(),forEach(),map(),for...of
用于循環對象屬性使用:for...in

以上所述是小編給大家介紹的JavaScript循環遍歷你會用哪些小結篇,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 夏津县| 长寿区| 临潭县| 营口市| 越西县| 奉新县| 彝良县| 吉木乃县| 齐齐哈尔市| 遵义县| 常熟市| 瑞安市| 门头沟区| 乾安县| 永和县| 六盘水市| 米易县| 清苑县| 会昌县| 昌宁县| 前郭尔| 朔州市| 平度市| 郑州市| 永顺县| 明光市| 柳林县| 留坝县| 丰顺县| 扶沟县| 库伦旗| 衡山县| 吉木萨尔县| 石门县| 廊坊市| 孝昌县| 宾阳县| 九龙县| 正蓝旗| 巴里| 忻城县|