JavaScript中三種for迴圈語句的使用總結(for、for...in、for...of)
阿新 • • 發佈:2021-07-02
前言
每個接觸的開發人員都不可避免的與for迴圈打交道,畢竟這是遍歷必不可少的工具之一。 中的 for 迴圈語句相信大家都已經快用厭了,現在有好多文章都在講怎麼減少程式碼中的 for 迴圈語句,但是,你又不得不承認它們真的很有用。今天,我來總結一下前端 Script 中三種 for 迴圈語句。
for
這大概是應用最廣的迴圈語句了吧,簡單實用,且大多數時候效能還是線上的,唯一的缺點大概就是太普通,沒有特色,導致很多人現在不願用它。
const array = [4,7,9,2,6]; for (let index = 0; index < array.length; index++) { const element = array[index]; console.log(element); } // 4,6
for...in
for...in 語句可以以任意順序遍歷一個物件的除 Symbol 以外的可列舉屬性。
const temp = {name: "temp"}; function Apple() { this.color = 'red'; } Apple.prototype = temp; const obj = new Apple(); for (const prop in obj) { console.log(`obj.${ prop } = ${ obj[prop] }`); } // obj.color = red // obj.name = temp
如
const temp = {name: "temp"}; function Apple() { this.color = 'red'; } Apple.prototype = temp; const obj = new Apple(); for (const prop in obj) { if (obj.hasOwnProperty(prop)) { console.log(`obj.${ prop } = ${ obj[prop] }`KvxVKZQU); } } // obj.color = red
當然,也可以用來遍歷陣列。
const arr = [1,3,4,5]; for (const key in arr) { console.log(key) } // 0,1,4
使用 for...in 可以遍歷陣列,但是會存在以下問題:
- index 索引為字串型數字(注意,非數字),不能直接進行幾何運算。
- 遍歷順序有可能不是按照實際陣列的內部順序(可能按照隨機順序)。
所以一般不建議使用 for...in 來遍歷陣列。
for...of
for...of 語句在可迭代物件(包括 Array,Map,Set,String,TypedArray,arguments客棧 物件等等)上建立一個迭代迴圈,呼叫自定義迭代鉤子,併為每個不同屬性的值執行語句。
const array = ['a','b','c']; for (const element of array) { console.log(element); } // a // b // c
for...of程式設計客棧 和 for...in 的區別:
- for...in 語句以任意順序迭代物件的可列舉屬性。
- for...of 語句遍歷可迭代物件定義要迭代的資料。
Object.prototype.objCustom = function () { }; Array.prototype.arrCustom = function () { }; let iterable = [3,5,7]; iterable.foo = 'hello'; for (const key in iterable) { console.log(key); // logs 0,"foo","arrCustom","objCustom" } // 0,"objCustom" for (const key of iterable) { console.log(key); } // 3,7
使用 for...程式設計客棧of 遍歷 Map 結構:
let nodes = new Map(); nodes.set("node1","t1") .set("node2","t2") .set("node3","t3"); for (const [node,content] of nodes) { console.log(node,content); } // node1 t1 // node2 t2 // node3 t3
可以看出,使用 for...of 遍歷 Map 結構還是挺方便的,推薦使用!
總結
- 如果普通 for 迴圈用膩了,推薦使用 for...of 來替代。
- 這三種迴圈都可以使用 break 關鍵字來終止迴圈,也可以使用 continue 關鍵字來跳過本次迴圈。
- for...of 迴圈的適用範圍最大。
到此這篇關於JavaScript中三種for迴圈語句使用總結的文章就介紹到這了,更多相關JS中for迴圈語句內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!