JavaScript ES6 中更簡易的迴圈寫法for … of 處理陣列字串

6 月 24, 2019 | | 0 條留言

過去我們可以使用 for, while, do while, for…in 等內在的函式來處理資料,而在 ES6 中我們多了 for…of 這個簡易的用法來處理這些疊代型的資料(iterable objects),包含陣列、字串、map、set、等等…。

陣列中 for…of 的基本用法

for…of 的使用非常簡單,以陣列為例:

let arr = [10, 20, 30]

for(let value of arr){
  console.log(value);  // 10, 20, 30
}

只要用這樣的方式,就可以把陣列的值一個個取出,不用像過去寫一大串像是 for(let i = 0; i < arr.length; i++){…} 是不是方便許多呢

for…of 的其它用法

for…of 除了用在陣列之外,也可以用在其他的資料型態,像是字串、map、set 等等…,舉字串為例:

let string = ES6;

for(let value of string){
  console.log(value);  // E, S, 6
}

是不是非常方便呢?

資料來源: https://pjchender.blogspot.com/2017/01/javascript-es6-for-of.html