【发布时间】:2014-03-05 02:29:37
【问题描述】:
我在使用来自 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”语句。如果它曾经执行过这个块,我希望循环停止。
在阅读了几篇关于它的帖子后,我意识到我不能在这个 forEach 函数中使用 break 语句。我尝试了使用“every”的建议here,但是当我使用这个包装在函数中时,我无法返回真值或假值。
我想避免使用任何类型的“休息”或破解来休息,但如果这是唯一的方法,我会使用它。如果有人对我如何重新设计我的逻辑有任何建议或有任何建议,我将不胜感激。我将在下面的伪代码中列出我的逻辑。
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 语句为真,它仍然会迭代数组的其余部分,即使他们只提交 1 个猜测,也会给 playerGuessCount 添加 1。 .forEach 严格用于检查他们的猜测是否重复。
这是我对“每个”http://repl.it/P74的尝试
【问题讨论】:
-
为什么
every不起作用? -
JavaScript 没有 forEach 函数。看起来您正在使用实现该功能的框架。也许尝试只返回 false?
-
@MjrKusanagi Array.prototype.forEach
-
我会再次尝试计算每一个,当我使用它时,我将它包装在另一个函数中,并在 If 语句中使用该函数。我遇到的问题是它没有返回真或假。当我将它从我包裹的函数中取出时,它在全局空间中,它工作得很好,但我不能将它保存在全局空间中。我会再试一次并添加一个 repl.it 链接。谢谢!
-
您能否发布不适用于
every的代码?它应该工作得很好......
标签: javascript arrays foreach