--- tags: JavaScript title: JavaScript - for of、forEach --- ###### tags: `JavaScript` `for of` `forEach` ###### *date: 2022 / 11 / 1* # ✏ for of 與 forEach 差別 我們在開發時,經常使用 `for of `和 `forEach` 的迴圈方法去處理資料,但會因為使用情境的不同,而去使用不同的迴圈方法,接下來讓我們介紹兩者的差異性與應用情境。 ## 資料範例: **1. 陣列資料** ```jsx= const numArr = [1, 2, 3]; ``` **2. 字串資料** ```jsx= const str = "hello,world"; ``` ## forEach **1. 只能使用在陣列資料** ```jsx= // 陣列 numArr.forEach((num) => { console.log(num); // 1 2 3 }); // 字串 str.forEach((s) => { console.log(s); // Uncaught TypeError: str.forEach is not a function }); ``` **2. 無法使用 break 中斷迴圈,或 return 返回值,會遍歷「陣列」的值到最後**。 ```jsx= numArr.forEach((num) => { if (num === 2) return; console.log(num); // 1 3 }); ``` **3. 無法使用在類陣列** ```jsx= function fn() { // 1. 類陣列 console.log(arguments); // 錯誤:Uncaught TypeError: arguments.forEach is not a function // arguments.forEach(item => { // console.log(item); // }); // 2. 解決方法,使用 ...展開運算子將類陣列轉為純陣列 console.log( [...arguments]); [...arguments].forEach(item => { console.log(item); }); }; fn('小明', '杰倫', '漂亮阿姨', '小美'); ``` ## for...of 是 ES6 標準才有的用於處理迴圈的方法,並且可以優化 `for`、`for in`、`forEach`等方法。 **1. 除了陣列資料以外,字串也可以使用** ```jsx // 陣列 for(const num of numArr) { console.log(num); // 1 2 3 }; // 字串 for(const s of str) { console.log(s); // h e l l o , w o r l d }; ``` **2. 可以被中斷迴圈執行,可搭配 break、continue、return 語法使用。** ```jsx= for (const num of numArr) { if (num === 2) { break; }; console.log(num); // 1 }; ``` **3. 可以使用在類陣列** ```jsx= function fn() { console.log(arguments); for (const argument of arguments) { console.log(argument); }; }; fn('小明', '杰倫', '漂亮阿姨', '小美'); ``` ### 總結 **forEach:** 適用於`需要知道索引值`的數組遍歷,且不能被中斷。 **for of:** 適用於`無須知道索引值`得數組遍歷,且`可以被中斷`,例外也可以`使用在字串與類陣列`中。 --- ### 參考文章: [JavaScript ES6 for...of 迴圈](https://www.fooish.com/javascript/ES6/for-of.html) [JS - for 迴圈與 forEach 有什麼不同](https://ithelp.ithome.com.tw/articles/10249305) [for in , for of 和forEach三者对比](https://blog.csdn.net/baidu_33438652/article/details/107266260)