【问题标题】:Add a compound AND condition that allows the loop to continue to iterate only if添加复合 AND 条件,仅在以下情况下允许循环继续迭代
【发布时间】:2018-06-22 22:56:46
【问题描述】:

我在做一个练习,这些是要求:

使用 For 循环遍历中奖号码数组中的每个位置,并将客户号码与数组包含的每个号码进行比较。

要完成此操作,您需要设置以下内容。

  1. 循环的计数器变量(例如 i)。
  2. 一个布尔变量(例如匹配项),用于标记是否找到匹配项。
  3. 仅允许循环继续迭代的复合 AND 条件 如果未找到匹配项,并且尚未到达数组末尾。
  4. 嵌套在 For 循环内的 if 语句用于检查客户 number 对数组中的每个中奖号码,每次循环 如果找到匹配项,则迭代并将布尔值 match 设置为 true。

到目前为止我所做的工作,但我不明白要求 3 会去哪里或需要它(因为 for 循环已经检查到数组的末尾没有到达?所以它肯定只需要一个if 语句而不是复合语句?),有人可以解释一下吗?

到目前为止我所拥有的:

var customerNumbers = 12;
var winningNumbers = [];
var match = false;

// Adds the winning numbers to winningNumbers
winningNumbers.push(12, 17, 24, 37, 38, 43);

// Messages that will be shown
var winningMessage = "This Week's Winning Numbers are:\n\n" + winningNumbers + "\n\n";
var customerMessage = "The Customer's Number is:\n\n" + customerNumbers + "\n\n";
var resultMessage = "Sorry, you are not a winner this week.";

// Searches the array to check if the customer number is a winner
for (var i = 0; i < winningNumbers.length; i++) {
	if (customerNumbers == winningNumbers[i]) {
		resultMessage = "We have a match and a winner!"
		match = true;
	}
}

// Result
alert(winningMessage + customerMessage + resultMessage);	

【问题讨论】:

  • 为什么不只是break 在你得到一个匹配之后?
  • 我假设您应该执行&amp;&amp; !match 之类的操作来提高性能?如果循环在找到匹配项时停止,而不是始终遍历整个数组,则程序会运行得更快。
  • @jhpratt 正是我的想法,但即使是 SO 也想知道为什么练习需要相同的额外和不需要的复合条件,而只要打破循环就足够了。除非该练习真正测试了该人对整个问题和解决方案本身的改进能力,否则理解问题更为重要。

标签: javascript loops for-loop if-statement conditional


【解决方案1】:

像这样将 and 语句添加到 for 条件中。
for (var i = 0; i &lt; winningNumbers.length &amp;&amp; !match; i++) {

if 语句不需要修改

var customerNumbers = 12;
var winningNumbers = [];
var match = false;

// Adds the winning numbers to winningNumbers
winningNumbers.push(12, 17, 24, 37, 38, 43);

// Messages that will be shown
var winningMessage = "This Week's Winning Numbers are:\n\n" + winningNumbers + "\n\n";
var customerMessage = "The Customer's Number is:\n\n" + customerNumbers + "\n\n";
var resultMessage = "Sorry, you are not a winner this week.";

// Searches the array to check if the customer number is a winner
for (var i = 0; i < winningNumbers.length && !match; i++) {
	if (customerNumbers == winningNumbers[i]) {
		resultMessage = "We have a match and a winner!"
		match = true;
	}
}

// Result
alert(winningMessage + customerMessage + resultMessage);	

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 2017-12-09
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多