About forEach () method does not use the break out of the loop problem

js programming syntax of the break statement:

The program will run the break statement immediately exits included in the innermost loop or exit a switch statement.

Because it is used to exit the loop or switch statement, so only when it appears in native For example: for () loop while () loop do-while () loop these statements, this form of break statement is legitimate.

So, for example, if we want to jump out of forEach () this cycle, how to write our code?

The answer is simple

Instead of using a return break

Look at the code

          newPieData.forEach(newItem => {
            if (newItem.business === oldItem.business) {
              // 该业务下已存在该成员,不添加该数据
              allowed = false
              // break   forEach()循环中不能使用break跳出循环
              // 这里我们使用return
              return
            }
          });

The return statement is used to specify the value returned by the function. return statement can only appear in the body of the function, appear in the code of any other place will cause a syntax error!

 

Guess you like

Origin blog.csdn.net/qq_36742720/article/details/93223955