前端 JavaScript 中的三種 for 迴圈語句總結

程式設計三昧發表於2021-06-27

迴圈

JavaScript 中的 for 迴圈語句相信大家都已經快用厭了,現在有好多文章都在講怎麼減少程式碼中的 for 迴圈語句,但是,你又不得不承認它們真的很有用。今天,我來總結一下前端 JavaScript 中三種 for 迴圈語句。

for

這大概是應用最廣的迴圈語句了吧,簡單實用,且大多數時候效能還是線上的,唯一的缺點大概就是太普通,沒有特色,導致很多人現在不願用它。

const array = [4, 7, 9, 2, 6];
for (const index = 0; index < array.length; index++) {
    const element = array[index];
    console.log(element);
}
// 4, 7, 9, 2, 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

如果你只要考慮物件本身的屬性,而不是它的原型,那麼使用 getOwnPropertyNames() 或執行 hasOwnProperty() 來確定某屬性是否是物件本身的屬性。

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] }`);
    }
}

// obj.color = red

當然,也可以用來遍歷陣列。

const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
    console.log(key)
}
// 0,1,2,3,4

使用 for...in 可以遍歷陣列,但是會存在以下問題:

  1. index 索引為字串型數字(注意,非數字),不能直接進行幾何運算。

  2. 遍歷順序有可能不是按照實際陣列的內部順序(可能按照隨機順序)。

所以一般不建議使用 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...offor...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, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"

for (const key of iterable) {
    console.log(key);
}
// 3, 5, 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 結構還是挺方便的,推薦使用!

總結

  1. 如果普通 for 迴圈用膩了,推薦使用 for...of 來替代。
  2. 這三種迴圈都可以使用 break 關鍵字來終止迴圈,也可以使用 continue 關鍵字來跳過本次迴圈。
  3. for...of 迴圈的適用範圍最大。

~

~ 本文完,感謝閱讀!

~

學習有趣的知識,結識有趣的朋友,塑造有趣的靈魂!

我是〖程式設計三昧〗的作者 隱逸王,我的公眾號是『程式設計三昧』,歡迎關注,希望大家多多指教!

你來,懷揣期望,我有墨香相迎! 你歸,無論得失,唯以餘韻相贈!

知識與技能並重,內力和外功兼修,理論和實踐兩手都要抓、兩手都要硬!

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章