添加一个复合AND条件,允许循环仅在以下情况下继续迭代

时间:2018-01-13 20:10:53

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

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

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

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

  1. 循环的计数器变量(例如i)。
  2. 一个布尔变量(例如匹配),用于标记是否已找到匹配项。
  3. 复合AND条件,允许循环仅继续迭代 如果找不到匹配项,并且尚未到达数组的末尾。
  4. if语句嵌套在For循环中,用于检查客户 数字对阵列中的每个获胜号码,每次循环 迭代,并在找到匹配项时将布尔匹配设置为true。
  5. 到目前为止我的工作原理但我不明白需求3的位置或需要它(因为for循环已经检查到数组的末尾还没有到达?所以肯定只需要一个如果陈述而不是复合词?),有人可以解释一下吗?

    到目前为止我所拥有的:

    
    
    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);	
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:1)

将for语句添加到for条件中 for (var i = 0; i < winningNumbers.length && !match; i++) {

无需更改if语句

&#13;
&#13;
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);	
&#13;
&#13;
&#13;