# 「译」forEach循环中你不知道的3件事

## 前言

### 正文

#### 1. return不会停止循环

array = [1, 2, 3, 4];
array.forEach(function (element) {
console.log(element);

if (element === 2)
return;

});
// Output: 1 2 3 4


MDN官方文档：

const array = [1, 2, 3, 4];
const callback = function(element) {
console.log(element);

if (element === 2)
return; // would this make a difference? no.
}
for (let i = 0; i < array.length; i++) {
callback(array[i]);
}
// Output: 1 2 3 4


#### 2. 不能break

const array = [1, 2, 3, 4];
array.forEach(function(element) {
console.log(element);

if (element === 2)
break;
});
// Output: Uncaught SyntaxError: Illegal break statement


const array = [1, 2, 3, 4];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);

if (array[i] === 2)
break;
}
// Output: 1 2


#### 3. 不能continue

const array = [1, 2, 3, 4];
array.forEach(function (element) {
if (element === 2)
continue;

console.log(element);
});
// Output: Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement


for (let i = 0; i < array.length; i++) {
if (array[i] === 2)
continue;
console.log(array[i]);
}
// Output: 1 3 4


#### 译者补充

forEach函数的实际运行原理其实是这样的，伪代码如下：

let arr = [1, 2];
arr.forEach(function(ele) {
console.log(ele);
});
// output: 1, 2
// 上面代码等同于
function func(ele) {
console.log(ele);
}
for (let i = 0; i < arr.length; i++) {
func(arr[i])
}
// output: 1, 2


let arr = [1, 2];
let sum = 0;
return a;
}
arr.forEach(async function(ele) {
});
console.log(sum);
// Output：0


let arr = [1, 2];
let sum = 0;