八个理由告诉你,请停止使用 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前端开发
相关推荐

2020-10-23 09:57:23

TypeScriptany代码

2023-08-29 17:47:02

嵌套 if开发

2020-04-14 12:12:20

JavaScriptIIFE函数

2022-10-30 16:27:38

Java移动应用程序开发

2010-04-25 23:21:57

2013-09-22 17:08:37

RSA加密组件

2018-03-13 13:00:19

虚拟化数据中心云计算

2016-12-13 19:40:00

大数据

2017-09-18 13:34:44

Facebook

2011-08-01 14:33:44

SQL

2016-02-22 10:46:02

Java排行第一

2010-04-14 10:43:55

2023-11-27 12:21:55

2020-07-15 10:32:34

5G网络华为

2022-03-16 00:07:55

OAuth2授权框架

2016-11-09 19:50:43

对象存储AWS S3

2023-02-20 15:48:48

2024-04-01 07:51:49

Exclude​工具类型TypeScript

2024-03-21 09:58:27

ExtractTypeScript工具类型

2015-06-23 09:10:04

Spark主机托管云平台
点赞
收藏

51CTO技术栈公众号