文章目录

  • 正常操作
  • 1、break跳出循环
  • 2、使用return
  • 非正常操作
  • 正确遍历数组并合适时跳出


lua 跳出本次循环 foreach跳出本次循环_数组

forEach 是一个用于数组的迭代方法,通常用于对数组的每个元素执行一个函数。与传统的 for 循环不同,forEach 不提供直接的方法来跳出循环。它会迭代数组的每个元素,而且无法在循环过程中中途终止。

正常操作不可以跳出循环,但非正常操作可以。

正常操作

1、break跳出循环

const forEachArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
forEachArray.forEach(item => {
	if(item === 'd') break
	console.log(item)
})

会报错 Module parse failed: Unsyntactic break 这是有语法错误的

2、使用return

const forEachArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
forEachArray.forEach(item => {
	if(item === 'd') return ''
	console.log(item)
})

无论return任何内容 false 0 null undefined, 整个遍历仍然会完整地执行。

非正常操作

通过try catch 抛出异常来终结forEach的遍历

const forEachArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']

try {
  forEachArray.forEach((item) => {
    if (item === 'd') {
      throw new Error("到d就停止吧");
    }
    console.log(item)
  })
} catch (e) {
  console.log(e.message); // 到d就停止吧
}

为什么说这是骚操作,正常开发能为了跳出数组遍历的循环,抛出一个异常?

正确遍历数组并合适时跳出

const forEachArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']

for(item of forEachArray) {
  if(item === 'd') break;
  console.log(item)
}

数组支持for of循环,for of循环可以使用break跳出循环。

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 3) {
    break; // 当元素等于3时,跳出循环
  }
  console.log(arr[i]);
}

最简单的for循环也是支持跳出的。

扩展阅读

forEach 是 JavaScript 数组对象上的一种常用的迭代方法,它用于遍历数组中的每个元素,并对每个元素执行指定的回调函数。以下是有关 forEach 的一些重要信息和用法示例:

语法:

array.forEach(callback(currentValue [, index [, array]])[, thisArg]);
  • callback:要执行的函数,它接受三个参数:
  • currentValue:当前正在处理的数组元素的值。
  • index(可选):当前正在处理的数组元素的索引。
  • array(可选):数组本身。
  • thisArg(可选):在回调函数中使用的可选值,用作 this 关键字的值。

示例:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function (value, index, array) {
  console.log(`Value: ${value}, Index: ${index}`);
});

// 输出:
// Value: 1, Index: 0
// Value: 2, Index: 1
// Value: 3, Index: 2
// Value: 4, Index: 3
// Value: 5, Index: 4

forEach 迭代数组的每个元素,为每个元素调用回调函数。这个方法通常用于在数组的每个元素上执行某些操作,例如打印元素、修改元素的值,或者执行其他操作。

需要注意的是,forEach 不会改变原始数组,它只是用于迭代。如果需要对数组进行修改或生成一个新的数组,你可能需要考虑使用其他数组方法,例如 mapfilterreduce 等。

另外,与一些其他迭代方法不同,forEach 不提供一种简单的方式来中途跳出循环或在回调函数中返回一个值。如果需要这样的控制,可能需要选择其他迭代方法,或者结合 for 循环来实现。