Javascript跳过函数

Javascript skips function

本文关键字:函数 Javascript      更新时间:2024-07-04

我正在为入门编程类做一个项目,所以我使用的是基本的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.");
}

您有;

if(numTrees == 5, 10)​

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

if(numTrees >= 5 && numTrees <= 10)

在这一行中使用逗号的方式有一个特殊的含义:

if(numTrees == 5, 10)​

本质上,它的作用是在转换为布尔值时返回10(第二个操作数)的值,而不是0,因此它是真的。

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

您可能打算使用OR(||):

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

或者对照范围检查numTrees

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

顺便说一句,在javascript中,建议您始终使用身份比较(===)而不是常规比较(==):

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

if(numTrees == 5, 10)​并不意味着If numtrees is equal to 5,6,7,8,9, or 10

将其更改为

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

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

这是一个奇怪的结构,我以前从未见过。我假设你相信这意味着"numTrees在5到10之间吗?",但事实并非如此。如果不检查,我认为这本质上意味着你同时检查两件事:

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

由于您要检查的第二个条件总是真的,所以您总是将答案设置为"是"。因此,循环总是只运行一次——它启动,检查答案是"否",将答案设置为"是",然后立即停止循环。

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

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

    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";
    }