问题
我们知道这东西有区别,但具体区别是什么呢?
使用限制
- for
无任何限制, 想怎么循环怎么循环- forEach
必须得在原型上有这个东西。
continue和break
- for
想怎么用怎么用- forEach
无效, 甚至还报错
异步阻碍
// 模拟请求
function axios(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, timeout)
})
}
(async function () {
console.log("start");
// for循环 可以等待
// for (let index = 0; index < 10; index++) {
// await axios(3000);
// await axios(3000);
// console.log("你好");
// }
// forEach循环 不会等待
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
arr.forEach(async () => {
await axios(3000);
await axios(3000);
console.log("你好");
break
})
})()
由上代码可得
- for循环异步会逐条等待
- forEach循环异步会一股脑执行
最后
做爬虫的时候需要间隔时间, 这个时候建议用原生的for循环