1

我正在为一个介绍性编程课程做一个项目,所以我使用的是基本的 javascript。这是我们第一个具有功能的项目,由于某种原因,我似乎无法使其工作。我在程序启动之前调用了所有变量并创建了函数,但由于某种原因,它跳过了在我的程序中运行该函数。任何帮助,将不胜感激。

这只是我的程序的开始,我不想写其余的代码,直到我弄清楚为什么这部分被破坏了,这就是为什么程序不做任何事情,如果它没有通过测试就关闭窗口。

// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";

function treeFunction(answer, counter, numTrees) {
    while (answer == "no" && counter < 3) {
        if (numTrees == 5, 10) {
            answer = "yes";
        } else if (numTrees < 5 || numTrees > 10) {
            alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
            answer = "no";
            numTrees = prompt("Please reenter the amount of trees in your sample.");
            counter + 1;
        }
    }
    if (answer == "no") {
        alert("You have entered an incorrect number too many times.\nThe Program will now end.");
        window.open('', '_self', '');
        window.close();
    } else if (answer == "yes") {
        return;
    }
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees); {
    document.write("<br/> <br/>" + "End of Program.");
}
4

5 回答 5

7

你有;

if(numTrees == 5, 10)​

错误的逗号导致if评估真值表达式10,因此它总是通过测试,测试 5、6、7、8、9 或 10;

if(numTrees >= 5 && numTrees <= 10)
于 2012-08-01T15:15:34.640 回答
2

The way you are using the comma in this line has a special meaning:

if(numTrees == 5, 10)​

Essentially what this does is returns the value of 10 (the second operand) when cast to a boolean, which is not 0, so it is true.

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comma_Operator

You probably meant to use OR (||):

if(numTrees == 5 || numTrees == 10)​

Or check numTrees against a range:

if(numTrees >= 5 || numTrees <= 10)​

On a side note, in javascript it is recommended that you always use identity comparison (===) instead of regular comparison (==):

if(numTrees === 5 || numTrees === 10)​
于 2012-08-01T15:19:07.320 回答
1
于 2012-08-01T15:18:54.800 回答
1

if (numTrees == 5, 10) { answer = "yes"; }

这是一个我从未见过的奇怪结构。我假设您认为这意味着“numTrees 在 5 到 10 的范围内吗?”,但事实并非如此。如果不检查,我认为这本质上意味着您要同时检查两件事:

  • numTrees 等于 5 吗?
  • 是 10 吗?(这本质上意味着“是 10 而不是 0”,这当然总是正确的)。

由于您检查的第二个条件始终为真,因此您始终将答案设置为“是”。结果,您的循环总是只运行一次 - 它启动,检查答案是否为“否”,将答案设置为“是”,然后立即停止循环。

您需要将条件更改为 if(numTrees >= 5 && numTrees <= 10)

于 2012-08-01T15:21:32.493 回答
0

你想要的是更像这样的东西:

    if (numTrees < 5 || numTrees > 10) {
        alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
        answer = "no";
        numTrees = prompt("Please reenter the amount of trees in your sample.");
        counter + 1;
    } else {
        answer = "yes";
    }
于 2012-08-01T15:18:45.667 回答