成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

八個理由告訴你,請停止使用 forEach 函數

開發 前端
8 個理由告訴你,請停止使用 forEach 函數。下面來看看都有哪些。

1.不支持處理異步函數

async function test() {
    let arr = [3, 2, 1]
    arr.forEach(async item => {
        const res = await mockSync(item)
        console.log(res)
    })
    console.log('end')
}
function mockSync(x) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
                resolve(x)
        }, 1000 * x)
    })
}
test()
Desired result:
3
2 
1
end
Actual results:
end
1
2
3

JavaScript 中的 forEach() 方法是一個同步方法,它不支持處理異步函數。

如果在forEach中執行了一個異步函數,forEach()不能等待異步函數完成,它會繼續執行下一項。 這意味著如果在 forEach() 中使用異步函數,則無法保證異步任務的執行順序。

替代 forEach

1.1 使用 map(), filter(), reduce()

他們支持在函數中返回 Promise,并會等待所有 Promise 完成。

使用map()和Promise.all()處理異步函數的示例代碼如下:

const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(num * 2);
    }, 1000);
  });
}
const promises = arr.map(async (num) => {
  const result = await asyncFunction(num);
  return result;
});
Promise.all(promises).then((results) => {
  console.log(results); // [2, 4, 6, 8, 10]
});

由于我們在async函數中使用了await關鍵字,map()方法會等待async函數完成并返回結果,以便我們正確處理async函數。

1.2 使用for循環

const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(num * 2);
    }, 1000);
  });
}
async function processArray() {
  const results = [];
  for (let i = 0; i < arr.length; i++) {
    const result = await asyncFunction(arr[i]);
    results.push(result);
  }
  console.log(results); // [2, 4, 6, 8, 10]
}
processArray();

2.無法捕獲異步函數中的錯誤

如果異步函數在執行時拋出錯誤,則 forEach() 無法捕獲該錯誤。 這意味著即使 async 函數發生錯誤,forEach() 也會繼續執行。

3. 除了拋出異常外,沒有辦法中止或跳出 forEach() 循環

forEach() 方法不支持使用 break 或 continue 語句來中斷循環或跳過項目。 如果需要跳出循環或跳過某個項目,則應使用 for 循環或其他支持 break 或 continue 語句的方法。

4.forEach刪除自己的元素,索引無法重置

在forEach中,我們無法控制index的值,它會無意識地增加,直到大于數組長度,跳出循環。 因此,也不可能通過刪除自身來重置索引。 

讓我們看一個簡單的例子:

let arr = [1,2,3,4]
arr.forEach((item, index) => {
    console.log(item); // 1 2 3 4
    index++;
});

5.這指向問題

在 forEach() 方法中,this 關鍵字引用調用該方法的對象。 但是,當使用普通函數或箭頭函數作為參數時,this 關鍵字的作用域可能會導致問題。 在箭頭函數中,this 關鍵字引用定義該函數的對象。

在普通函數中,this 關鍵字指的是調用該函數的對象。 如果需要保證this關鍵字的作用域是正確的,可以使用bind()方法綁定函數的作用域。 

以下是 forEach() 方法中 this 關鍵字范圍問題的示例:

const obj = {
  name: "Alice",
  friends: ["Bob", "Charlie", "Dave"],
  printFriends: function () {
    this.friends.forEach(function (friend) {
      console.log(this.name + " is friends with " + friend);
    });
  },
};
obj.printFriends();

在這個例子中,我們定義了一個名為 obj 的對象,它有一個 printFriends() 方法。 

在 printFriends() 方法中,我們使用 forEach() 方法遍歷 friends 數組,并使用普通函數打印每個朋友的名字和 obj 對象的 name 屬性。 

但是,當我們運行這段代碼時,輸出是:

undefined is friends with Bob
undefined is friends with Charlie
undefined is friends with Dave

這是因為,在forEach()方法中使用普通函數時,函數的作用域不是調用printFriends()方法的對象,而是全局作用域。 

因此,無法在該函數中訪問 obj 對象的屬性。

要解決這個問題,可以使用bind()方法綁定函數作用域,或者使用箭頭函數定義回調函數。 下面是使用 bind() 方法解決問題的代碼示例:

const obj = {
  name: "Alice",
  friends: ["Bob", "Charlie", "Dave"],
  printFriends: function () {
    this.friends.forEach(
      function (friend) {
        console.log(this.name + " is friends with " + friend);
      }.bind(this)
    );
  },
};
obj.printFriends();

在本例中,我們使用bind()方法綁定函數作用域,將函數作用域綁定到obj對象上。 運行代碼后,輸出為:

Alice is friends with Bob 
Alice is friends with Charlie 
Alice is friends with Dave

通過使用bind()方法綁定函數作用域,我們可以正確訪問obj對象的屬性。

另一種解決方法是使用箭頭函數。 由于箭頭函數沒有自己的 this,它繼承了它所在作用域的 this。因此,在箭頭函數中,this 關鍵字指的是定義該函數的對象。

6、forEach的性能低于for循環

for:for循環沒有額外的函數調用棧和上下文,所以它的實現最簡單。

forEach:對于forEach,其函數簽名包含參數和上下文,因此性能會低于for循環。

7.刪除或未初始化的項目將被跳過

const array = [1, 2, /* empty */, 4];
let num = 0;
array.forEach((ele) => {
  console.log(ele);
  num++;
});
console.log("num:",num);
//  1
//  2 
//  4 
// num: 3
const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
  if (word === 'two') {
    words.shift(); 
  }
}); // one // two // four
console.log(words); // ['two', 'three', 'four']

8. forEach的使用不會改變原來的數組

調用 forEach() 時,它不會更改原始數組,即調用它的數組。 但是那個對象可能會被傳入的回調函數改變。

// 1
const array = [1, 2, 3, 4]; 
array.forEach(ele => { ele = ele * 3 }) 
console.log(array); // [1,2,3,4]
const numArr = [33,4,55];
numArr.forEach((ele, index, arr) => {
    if (ele === 33) {
        arr[index] = 999
    }
})
console.log(numArr);  // [999, 4, 55]
// 2
const changeItemArr = [{
    name: 'wxw',
    age: 22
}, {
    name: 'wxw2',
    age: 33
}]
changeItemArr.forEach(ele => {
    if (ele.name === 'wxw2') {
        ele = {
            name: 'change',
            age: 77
        }
    }
})
console.log(changeItemArr); // [{name: "wxw", age: 22},{name: "wxw2", age: 33}]
const allChangeArr = [{    name: 'wxw',    age: 22}, {    name: 'wxw2',    age: 33}]
allChangeArr.forEach((ele, index, arr) => {
    if (ele.name === 'wxw2') {
        arr[index] = {
            name: 'change',
            age: 77
        }
    }
})
console.log(allChangeArr); // // [{name: "wxw", age: 22},{name: "change", age: 77}]

寫在最后

以上就是我今天想與您分享的8個關于不要再隨意使用ForEach的函數的理由。


責任編輯:華軒 來源: web前端開發
相關推薦

2024-05-10 12:29:30

接口類型

2020-10-23 09:57:23

TypeScriptany代碼

2024-09-29 07:00:00

JavaScriptTypeScriptfor...of循環

2024-09-28 10:13:14

2023-08-29 17:47:02

嵌套 if開發

2022-10-30 16:27:38

Java移動應用程序開發

2020-04-14 12:12:20

JavaScriptIIFE函數

2024-06-03 00:01:00

2010-04-25 23:21:57

2011-08-01 14:33:44

SQL

2016-02-22 10:46:02

Java排行第一

2024-06-17 08:04:23

2013-09-22 17:08:37

RSA加密組件

2024-06-27 10:45:27

2018-03-13 13:00:19

虛擬化數據中心云計算

2016-12-13 19:40:00

大數據

2016-11-09 19:50:43

對象存儲AWS S3

2010-04-14 10:43:55

2023-11-27 12:21:55

2017-09-18 13:34:44

Facebook
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 中文字幕av网址 | 婷婷色在线 | 91视频网址 | 欧美色性 | 久久久久久久久淑女av国产精品 | 日韩一区二区在线免费观看 | 欧美日韩一区二区三区四区 | 精品成人一区 | 欧美福利网站 | 91精品国产色综合久久不卡98 | 亚洲精品在线视频 | 欧美日韩精品 | 综合久| 先锋资源在线 | 国产激情一区二区三区 | 亚洲九色 | 精品国产欧美日韩不卡在线观看 | 中文字幕1区2区 | 婷婷五月色综合 | 久久久精品网 | chinese中国真实乱对白 | 欧美另类视频在线 | 天天拍天天插 | 日韩国产中文字幕 | 亚洲一区二区成人 | 日韩久久久久 | 99久久久国产精品 | 91av久久久 | 欧美成人精品激情在线观看 | 久久国产精品精品 | www.9191| 成人黄色电影免费 | 久久久精品一区 | 亚洲欧美日韩精品久久亚洲区 | 久久人人网 | 四虎永久免费在线 | 黄色一级大片在线免费看产 | 日本黄色不卡视频 | 日韩欧美在线视频观看 | 青青草网 | 精品国产一区二区三区久久久蜜月 |