迭代陣列 forEach, for of, for in, map


Posted by mijouhsieh on 2023-03-01

 forEach((必)executor, (選)thisValue)

  • 對陣列中元素傳入executor中
  • 沒有任何回傳
    (必)executor: function | default:無
    (選)thisValue: object | default:undefined
  • executor依序接收3個參數:
    • 目前執行的元素
    • 目前執行的元素索引
    • 呼叫 reduce 方法的陣列,即原陣列 ??(補)
  • 若有空元素,會跳到下個元素


for (const element of iterable) {...}

  • 和forEach差異,若有空元素不會跳到下個元素,會顯示undefined
  • 若要取得索引,和 entries方法使用

for (const key in iterable) {...}

遍歷陣列中的 可列舉屬性
陣列也是物件,索引 也是 可列舉屬性 的一種
!! 若陣列新增 不是索引的屬性 ,也會被遍歷到(有bug)!!所以不推薦使用


map ((必)executor, (選)thisValue)

從第一個元素遍歷到最後一個,
不改原本的值
回傳 新陣列

  • executor依序接收3個參數:
    • 目前執行的元素
    • 目前執行的元素索引
    • 呼叫 map 方法的陣列,即原陣列

(必)executor: function | default:無
(選)thisValue: object | default: undefined


#foreach #for of #for in #map()







Related Posts

Web開發學習筆記16 — OOP(Object Oriented Programming)、Constructor Function、Class

Web開發學習筆記16 — OOP(Object Oriented Programming)、Constructor Function、Class

[JavaScript] ES6 其他好用的新語法

[JavaScript] ES6 其他好用的新語法

第四章:撰寫多商品單投資策略

第四章:撰寫多商品單投資策略


Comments