【问题标题】:Hide variables until needed?隐藏变量直到需要?
【发布时间】:2015-08-10 11:37:15
【问题描述】:

我有一个简单的计算器来计算几个形状的尺寸。它应该被设置为使第一个函数具有一组if 语句,这些语句根据用户输入触发一个且仅一个其他函数。但相反,无论我的答案是什么,它都会触发所有这些。这是因为所有变量提示都是公开的,它只是通过它们全部运行。我如何使它只运行与正在运行的函数相对应的函数?它也成功了,所以我所有的 console.log 结果都出现了 NaN。我该如何解决这个问题?

//主要功能

        function theConjurer() {
            firstQuestion = prompt("Hi! This is my shape dimension calculator! I have three different shapes in this version but I can always add more! For now I have these three:\nCircle Area\nSphere Volume\nRectangular Prism Volume\n\nEnjoy!!!");
                return firstQuestion.toLowerCase(); //The answer to this prompt is supposed to spring one of the functions below.

            if(firstQuestion === "Circle" || firstQuestion === "Circle Area") { //If the answer is one of these strings, then it triggers the circle area function.
                console.log("You've slected Circle!")
                calcCircleArea();
            }

            else if(firstQuestion === "Sphere" || firstQuestion === "Sphere Volume") { //This one triggers the sphere volume function.
                console.log("You've slected Sphere!")
                calcSphereVolume();
            }

            else if(firstQuestion === "Prism" || firstQuestion === "Rectangular Prism" || firstQuestion === "Prism Volume" || firstQuestion === "Rectangular Prism Volume") { //This one is for volume of a rectangular prism.
                console.log("You've slected Rectangular Prism!")
                calcPrismVolume();
            }

            else {  //Anything else just brings up another prompt for the same answers.
                firstQuestion = prompt("Sorry, that's not one of the options I have right now. Try again!");
            }
        }

        theConjurer(); //To automatically bring up the starting function.


        //Function for Dimensions of a Circle

        var pi = 3.14; //pi rounded down to the hudredths place.
        var circleRadius = prompt("What is the radius of your circle?")

        calcCircleArea(pi, circleRadius); //Variable declarations.

        function calcCircleArea(p, r) { //
            var circleArea = p * Math.pow(r, 2);
            console.log("The circle you've entered is " + circleArea + " square units!");
        }


        //Function for Volume of a Sphere

        var fourThirds = (4/3);
        var radius = prompt("Do you know the diameter of your sphere? Just half that is your radius! What's the radius?"); //User input for the shape's radius.

        calcSphereVolume(fourThirds, pi, radius);

        function calcSphereVolume(f, p, r) {
            var sphereVolume = f * p * Math.pow(r, 3);
            console.log("Your sphere is " + sphereVolume + " cubed units! Congradulations!");
        }


        //Function for Dimensions of a Rectangular Prism

        var length = prompt("What's the length of this prism?"); //User input for the shape's length.
        var width = prompt("What's the width?"); //User input for the shape's width.
        var height = prompt("What is the height?"); //User input for the shape's height.

        calcPrismVolume(length, width, height); //Storage for the above three variables.

        function calcPrismVolume(l, w, h) { //Function and its parameters.
            var prismVolume = l * w * h; //New variable made from multiplying those parameters.
            console.log("Your prism is " + prismVolume + " cubed units!"); //Output of shape's area.
        }

【问题讨论】:

  • || OR 运算符用于条件列表而不是值列表...所以它是variable operator value1 || variable operator value2 而不是variable operator value1 || value2。试试if(firstQuestion === "Prism" || firstQuestion === "Rectangular Prism")
  • 需要注意的是["Sphere", "Sphere volume"].indexOf(firstQuestion) !== -1可以做,但是不能用OR加多个值,它只是分隔语句
  • 我可能不得不尝试 [ ] 选项。我使用 OR 运算符进行了您建议的更改,现在我输入的任何答案都会触发 else 语句。
  • 只要使用你的调试器,不要再问这样的基本问题了。对不起,这是我的看法。如果您查找“javascrpt prompt”、“javascript NaN”、“javascript type cast”等,您会在 Google 上找到十几个示例。

标签: javascript if-statement parameters var


【解决方案1】:

if(firstQuestion === "Circle" || "Circle Area") 总是评估为true,因为"Circle Area" 是一个真实的陈述。 尝试将其更改为 if(firstQuestion === "Circle" || firstQuestion === "Circle Area") 之类的内容。

【讨论】:

    【解决方案2】:

    你的语法没有你想的那样。例如,这行是错误的:

    if(firstQuestion === "Circle" || "Circle Area") { //If the answer is one of these strings, then it triggers the circle area function.
    

    这不会检查firstQuestion 是否是这些字符串中的任何一个。它检查两个条件之一是否为真或“真实”:(1)firstQuestion === "Circle" 或(2)"Circle Area"。也就是说,它将"Circle Area" 视为布尔表达式,而不是使用=== 进行比较的一部分。

    "Circle Area" 始终为真(换句话说,被视为布尔值,它的计算结果为true)。因此,您的 if 条件将始终得到满足。同样的事情发生在其他每个if 语句中。

    对于每个条件,您需要进行两次比较,如下所示:

    if(firstQuestion === "Circle" || firstQuestion === "Circle Area") { 
    

    您还需要提前添加几个elses 或return,所以您的主函数需要如下所示:

    //Main Function
    
        function theConjurer() {
            firstQuestion = prompt("Hi! This is my shape dimension calculator! I have three different shapes in this version but I can always add more! For now I have these three:\nCircle Area\nSphere Volume\nRectangular Prism Volume\n\nEnjoy!!!"); //The answer to this prompt is supposed to spring one of the functions below.
    
            if(firstQuestion === "Circle" || firstQuestion === "Circle Area") { //If the answer is one of these strings, then it triggers the circle area function.
                calcCircleArea();
            }
    
            else if(firstQuestion === "Sphere" || firstQuestion === "Sphere Volume") { //This one triggers the sphere volume function.
                calcSphereVolume();
            }
    
            else if(firstQuestion === "Prism" || firstQuestion === "Rectangular Prism" || firstQuestion === "Prism Volume" || firstQuestion === "Rectangular Prism Volume") { //This one is for volume of a rectangular prism.
                calcPrismVolume();
            }
    
            else {  //Anything else just brings up another prompt for the same answers.
                firstQuestion = prompt("Sorry, that's not one of the options I have right now. Try again!");
            }
        }
    

    更好的解决方案是使用switch/case/default 块,但这并不是绝对必要的。

    【讨论】:

    • 我尝试了该更改,现在它不接受我输入的任何内容,只是默认为 else 语句。
    • @MattLee 那是因为您正在为每种可能性做一个简单的if,而不是else if,并且您不会提前返回。因此,除非您的最后一个 if 得到满足,否则关联的 else 块将始终执行,即使其他 if 语句之一得到满足。
    • 我现在有 if else 语句。无论我输入什么,它仍然只是跳转到 Sphere 函数,即使我输入“Circle”。然后它继续到棱镜功能。
    • @MattLee 抱歉,试试修改后的版本。一分钟前遇到了一些复制粘贴问题。
    • 很抱歉,我不能使用 switch/case/default。这是课堂作业,我们没有涉及。我只是想知道我在使用我所拥有的代码时做错了什么,因为就目前而言,这就是我能够在这个作业中使用的全部内容。 if 和 else 以及 if else 语句、函数和循环。
    【解决方案3】:

    Matthew,您应该使用 Switch 语句来进行此类选择。更重要的是,您的代码中有很多错误。例如,您使用了 var p,但您在函数中使用了未定义的 pi 变量。我已经为你修好了。如果这个答案有帮助,请通过投票告诉我。

    我已经为你做了一个工作示例 JSFIDDLE --> http://jsfiddle.net/zpo4b3mo/

    //Lee_Matthew_Functions_Assignment_5/26/2015
    
    //Main Function
        var pi = 3.14; //pi rounded down to the hudredths place.
    
    function theConjurer() {
        var firstQuestion = prompt("Hi! This is my shape dimension calculator! I have three different shapes in this version but I can always add more! For now I have these three:\nCircle Area\nSphere Volume\nRectangular Prism Volume\n\nEnjoy!!!"); 
    
        switch(firstQuestion) {
            case "Circle" || "Circle Area":
                console.log('Selected Circle');
                calcCircleArea();
                break;
            case "Sphere" || "Sphere Volume":
                console.log('Selected Sphere');
                calcSphereVolume();
                break;
            case "Prism" || "Rectangular Prism" || "Prism Volume" || "Rectangular Prism Volume":
                console.log('Selected Prism');
                calcPrismVolume();
                break;
            default:  //Anything else just brings up another prompt for the same answers.
                console.log('None match');
                //firstQuestion = prompt("Sorry, that's not one of the options I have right now. Try again!");
                break;
        }
    
    }
    
    theConjurer(); //To automatically bring up the starting function.
    
    
    //Function for Dimensions of a Circle
    
    function calcCircleArea() {
        var radius = prompt('What is the radius?');
        var circleArea = pi * Math.pow(parseInt(radius), 2);
        console.log("The circle you've entered is " + circleArea + " square units!");
    }
    
    
    //Function for Volume of a Sphere
    
    function calcSphereVolume() {
        var f = (4/3);
        var r = prompt("Do you know the diameter of your sphere? Just half that is your radius! What's the radius?"); //User input for the shape's radius.
        var sphereVolume = f * pi * Math.pow(r, 3);
        console.log("Your sphere is " + sphereVolume + " cubed units! Congradulations!");
    }
    
    
        //Function for Dimensions of a Rectangular Prism
    
    
    function calcPrismVolume() {
    
        var l = prompt("What's the length of this prism?"); //User input for the shape's length.
        var w = prompt("What's the width?"); //User input for the shape's width.
        var h = prompt("What is the height?"); //User input for the shape's height.//Function and its parameters.
        var prismVolume = l * w * h; //New variable made from multiplying those parameters.
        console.log("Your prism is " + prismVolume + " cubed units!"); //Output of shape's area.
    }
    

    【讨论】:

    • 不幸的是,有些概念我不应该在这里使用,因为这是课堂作业,我们还没有讨论过它们。一种是switch/case/default。此外,我的三个底部函数的变量设置也是如此,因为我们必须在其中使用参数。我自己解决了 Circle 功能的问题。只是缺少一个变量。我仍然不知道如何阻止它调用所有三个函数,而不是只调用一个并停止。
    • 您能通过 jsfiddle 分享最新版本吗?我可以帮你查一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多