gpt4 book ai didi

javascript - 如何重组 .forEach 以便我可以摆脱它

转载 作者:行者123 更新时间:2023-11-28 19:57:58 25 4
gpt4 key购买 nike

我在使用来自 Ruby 背景的 JavaScript 和“break”语句时遇到了很多麻烦。

这是我的功能:

function isItTheNumber(numberToGuess){

if(previousGuess === null){
previousGuess = [playersGuess];
}

previousGuess.forEach(function(guess){
if(playersGuess === guess && previousGuess > 1){
textStatus.style.display = 'block';
textStatus.innerHTML = 'You already picked that number';
} else if(parseInt(playersGuess) === parseInt(numberToGuess)){
textStatus.style.display ='block';
textStatus.innerHTML = 'You Are CORRECT!';
} else {
previousGuess.push(playersGuess);
textStatus.style.display='block';
textStatus.innerHTML = 'You are ' + hotOrCold();
document.getElementById('guess-count').innerHTML = playerGuessCount++;
}
});
}

在我的 .forEach 循环中,我希望在第一个 if 语句中有一个“break”语句。我希望循环在执行此 block 时停止。

在阅读了一些有关它的文章后,我意识到我不能在这个 forEach 函数中使用break语句。我尝试了建议here使用“every”,但是当我在函数中使用它时,我无法返回 true 或 false 值。

我想避免使用任何类型的“中断”或破解来中断,但如果这是唯一的方法,我会使用它。如果有人对我如何重新设计我的逻辑有任何建议或有任何建议,我将不胜感激。我将在下面的伪代码中列出我的逻辑。

1) Check if the previousGuess array is null or populated. If it is null, set it to an array with the first value.
2) Iterate over the previousGuess array.
3) If: see if the user input (playerGuess) is in the previousGuess array. The previous guess
array must be larger than 1.
4) Else If: If the users guess is the same as the a the value, tell them they are correct.
5) Else: if the users guess isn't the same as the value, tell them and add 1 to the playerGuessCount.

我当前逻辑的问题是playerGuessCount被调用了太多次。如果数组被迭代并找到,并且第一个 if 语句为 true,它仍然会迭代数组的其余部分,即使他们只提交 1 个猜测,也将 1 添加到playerGuessCount。 .forEach 严格来说是为了检查他们的猜测是否重复。

这是我对“每个”的尝试http://repl.it/P74

最佳答案

您使用的 .forEach 方法是通过扩展函数原型(prototype)实现的包装器。

你可以打破传统的循环:

for (var key in objs){
var obj=objs[key];
//do your business here

break; //this line exists the loop
}

但是,如果使用回调函数,则必须通过放置“skip”变量来终止函数调用本身。

previousGuess.forEach(function(guess){
if (this.skip_the_foreach_loop) return;
if (need_to_exit) this.skip_the_foreach_loop=true;
});

不是最有效的方法,但可以节省一些 CPU 周期。

关于javascript - 如何重组 .forEach 以便我可以摆脱它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com