我們經常會用到js的各種循環,掌握他們之間的區別和各個跳出循環的方法對性能優化有極大的幫助
1.性能比較 : for>forEach>map
- for : for循環沒有額外的函數調用棧和上下文,所以它的實現最為簡單.
- forEach : 對於forEach來說,它的函數簽名中包含了參數和上下文,所以性能會低於 for 循環.
- map: map 會返回一個新的數組,數組的創建和賦值會導致分配內存空間,因此會帶來較大的性能開銷.
2.跳出循環的方法
2.1 for :使用break
for (let index = 0; index < 5; index++) { if(index>3){ break; } console.log(index);// 0 1 2 3 }
2.2 forEach / map : 使用try...catch
try { [0,1,2,3,4,5].forEach(element => { if(element>3){ throw new Error('Irregular element') } console.log(element);// 0 1 2 3 }); } catch (error) { console.log(error.toString());//Error: Irregular element }
2.3 for of :使用break
for (const ele of [0,1,2,3,4,5]) { if(ele>3){ break; } console.log(ele);// 0 1 2 3 }
3.相同效果的while循環
const arr = [0,11,22,33,44,55]; let i=0; while (arr[i]<=33) { console.log(arr[i]);// 0 11 22 33 i++; }
補充概念:可迭代對象:
ES6中引入了 iterable 類型,Array Set Map String arguments NodeList 都屬於 iterable, 他們特點就是都擁有 [Symbol.iterator] 方法,包含他的對象被認為是可迭代的 iterable。
判斷是否是可迭代對象:
const isIterable = obj => obj != null && typeof obj[Symbol.iterator] === 'function';
isIterable ('abc'); // true