如何停止 JavaScript 中的 forEach 循环?

作者: jie 分类: JavaScript 发布时间: 2023-08-08 15:18

面试官:你能停止 JavaScript 中的 forEach 循环吗?

在回答这个问题时,我的回答导致面试官突然结束了面试。

我对结果感到沮丧,问面试官:“为什么?实际上可以停止 JavaScript 中的 forEach 循环吗?”

在面试官回答之前,我花了一些时间解释我对为什么我们不能直接停止 JavaScript 中的 forEach 循环的理解。

我的答案正确吗?

小伙伴们,下面的代码会输出什么数字呢?

它会只输出一个数字还是多个数字?

是的,它会输出‘0’、‘1’、‘2’、‘3’。

const array = [-3, -2, -1, 0, 1, 2, 3]
array.forEach((it) => {
	if (it >= 0) {
		console.log(it)
		return // or break
	}
})

这是正确的!我向面试官展示了这段代码,但他仍然相信我们可以停止 JavaScript 中的 forEach 循环。

天哪,你一定是在开玩笑。

为什么?

为了说服他,我不得不再次实现forEach模拟。

Array.prototype.forEach2 = function(callback, thisCtx) {
	if (typeof callback !== 'function') {
		throw `${callback} is not a function`
	}
	const length = this.length
	let i = 0
	while (i < length) {
		if (this.hasOwnProperty(i)) {
			// Note here:Each callback function will be executed once
			callback.call(thisCtx, this[i], i, this)
		}
		i++
	}
}

是的,当我们使用“forEach”迭代数组时,回调将为数组的每个元素执行一次,并且我们无法过早地摆脱它。

例如,在下面的代码中,即使“func1”遇到break语句,“2”仍然会输出到控制台。

const func1 = () => {
	console.log(1)
	return
}
const func2 = () => {
	func1()
	console.log(2)
}
func2()

停止 forEach 的 3 种方法

你太棒了,但我想告诉你,我们至少有 3 种方法可以在 JavaScript 中停止 forEach。

1.抛出错误

当我们找到第一个大于或等于0的数字后,这段代码将无法继续。所以控制台只会打印出0。

const array = [-3, -2, -1, 0, 1, 2, 3]
try {
	array.forEach((it) => {
		if (it >= 0) {
			console.log(it)
			throw Error(`We've found the target element.`)
		}
	})
} catch (err) {}

哦!我的天啊!我简直不敢相信,这让我无法说话。

2.设置数组长度为0

请不要那么惊讶,面试官对我说。

我们还可以通过将数组的长度设置为0来中断forEach。如您所知,如果数组的长度为0,forEach将不会执行任何回调。

const array = [-3, -2, -1, 0, 1, 2, 3]
array.forEach((it) => {
	if (it >= 0) {
		console.log(it)
		array.length = 0
	}
})

3.使用splice删除数组的元素

思路和方法2一样,如果能删除目标元素后面的所有值,那么forEach就会自动停止。

const array = [-3, -2, -1, 0, 1, 2, 3]
array.forEach((it, i) => {
	if (it >= 0) {
		console.log(it)
		// Notice the sinful line of code
		array.splice(i + 1, array.length - i)
	}
})

我睁大了眼睛,我不想读这段代码。这不好。

请用for或some

我对面试官说:“哦,也许你是对的,你设法在 JavaScript 中停止了 forEach,但我认为你的老板会解雇你,因为这是一个非常糟糕的代码片段。

我不喜欢做那样的事;这会让我的同事讨厌我。”

也许我们应该使用“for”或“some”方法来解决这个问题。

1.for

const array = [-3, -2, -1, 0, 1, 2, 3]
for (let i = 0, len = array.length; i < len; i++) {
	if (array[i] >= 0) {
		console.log(array[i])
		break
	}
}

2. some

const array = [-3, -2, -1, 0, 1, 2, 3]
array.some((it, i) => {
	if (it >= 0) {
		console.log(it)
		return true
	}
})

发表回复