简单的 Javascript 程序:未捕获的 ReferenceError:x 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17395948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:10:49  来源:igfitidea点击:

Simple Javascript program: Uncaught ReferenceError: x is not defined

javascript

提问by Brian

I am stuck on an exercise that asks to create a simple calculator. The user input is delegated to a separate function so that I may expand the program to subtraction, multiplication and division without repeating lines.

我被困在一个要求创建一个简单计算器的练习中。用户输入被委托给一个单独的函数,这样我就可以将程序扩展为减法、乘法和除法,而无需重复行。

The error is:

错误是:

"Uncaught ReferenceError: x is not defined"

“未捕获的 ReferenceError:x 未定义”

<!DOCTYPE HTML>
<html>
    <head>
        <title>Lesson 6 Lab Exercise 3 - Calculator with user input</title>
            <script language="javascript" type="text/javascript">
                function getNumbers()
                {
                    var x = prompt("Enter the first number:");
                    var y = prompt("Enter the second number:");
                    x = parseInt(x);
                    y = parseInt(y);
                }

                function addition()
                {
                    getNumbers();   
                    document.write(x + "+" + y + "=" + (x+y));
                }
            </script>
    </head>
    <body>
        <input type="button" value="Add" onclick="addition()">
    </body>
</html>

回答by Andrey Shchekin

As other answers say, you should pass xand yfrom one function to another. I do not agree with the zmo's approach using array, so here is a short object option (main difference from karthikr's post is that it is shorter):

至于其他的答案说,你应该通过xy从一个功能到另一个。我不同意 zmo 使用数组的方法,所以这里有一个短对象选项(与 karthikr 的帖子的主要区别在于它更短):

function getNumbers()
{
    var x = prompt("Enter the first number:");
    var y = prompt("Enter the second number:");
    x = parseInt(x);
    y = parseInt(y);
    return { x: x, y: y };
}

function addition()
{
    var numbers = getNumbers();   
    document.write(numbers.x + "+" + numbers.y + "=" + (numbers.x+numbers.y));
}

Some additional information as requested in comments:

评论中要求的一些附加信息:

  1. { x: x, y: y }is an object defined using literal object notation (or object initializer).
    See Using object initializers (MDN).

  2. General form of that syntax is { property1: value1, property2: value2 /*, etc*/ }. This basically defines a map that allows you to get value1using key property1(similar to hashtables/dictionaries in other languages).
    So { x: x }defines an object where value of property xis equal to variable named x. This might be a bit confusing, but the property name and value are completely separate things and just happened to have the same name at this time.

  3. After the object has been defined, you can access property values by using several different approaches. Most common are object.property1or object['property1'].
    See Objects and properties (MDN).
  1. { x: x, y: y }是使用文字对象符号(或对象初始值设定项)定义的对象。
    请参阅使用对象初始值设定项 (MDN)

  2. 该语法的一般形式是{ property1: value1, property2: value2 /*, etc*/ }. 这基本上定义了一个允许您value1使用键的映射property1(类似于其他语言中的哈希表/字典)。
    因此{ x: x }定义了一个对象,其中属性的x值等于名为 的变量x。这可能有点令人困惑,但属性名称和值是完全不同的东西,此时恰好具有相同的名称。

  3. 定义对象后,您可以使用几种不同的方法访问属性值。最常见的是object.property1object['property1']
    请参阅对象和属性 (MDN)

Btw if there is a better tutorial than MDN please let me know and I'll update the links.

顺便说一句,如果有比 MDN 更好的教程,请告诉我,我会更新链接。

回答by TGH

                var x;
                var y;
                function getNumbers()
                {
                    x = prompt("Enter the first number:");
                    y = prompt("Enter the second number:");
                    x = parseInt(x);
                    y = parseInt(y);
                }

                function addition()
                {
                    getNumbers();   
                    document.write(x + "+" + y + "=" + (x+y));
                }

Define the variables outside of the function, so that they are in scope in both methods. You can define the entire code block in a closure to avoid adding the variables to global space.

在函数外部定义变量,以便它们在两种方法中都在范围内。您可以在闭包中定义整个代码块,以避免将变量添加到全局空间。

回答by HMR

Made some corrections to the code and added a check if both x and y are numbers.

对代码进行了一些更正,并检查了 x 和 y 是否都是数字。

<!DOCTYPE HTML>
<html>
    <head>
        <title>Lesson 6 Lab Exercise 3 - Calculator with user input</title>
            <script language="javascript" type="text/javascript">
              var Calculator={
                x:0,
                y:0,
                getNumbers:function()
                {
                    // reset x and y
                    this.x=NaN;
                    this.y=NaN;
                    while(isNaN(this.x)){
                      this.x = prompt("Enter the first number:");
                      this.x = parseFloat(this.x);
                    }
                    while(isNaN(this.y)){
                      this.y = prompt("Enter the second number:");
                      this.y = parseFloat(this.y);
                    }
                },
                addition:function()
                {
                    this.getNumbers();   
                    document.write(this.x + "+" + this.y + "=" + (this.x+this.y));
                }
              }
            </script>
    </head>
    <body>
        <input type="button" value="Add" onclick="Calculator.addition()">
    </body>
</html>

回答by zmo

You're problem is that xand yare defined within the getNumbers()function's scope. A bad solution would be to declare xand yin an outer scope, or worst at global scope. A good solution is to return the values of xand yfrom the getNumbersfunction and use them afterwards:

你的问题是,x并且y是在getNumbers()函数的范围内定义的。一个糟糕的解决方案是在外部范围内声明xand y,或者在全局范围内声明和最糟糕。一个好的解决办法是返回的值x,并ygetNumbers功能,之后使用它们:

 function getNumbers() {
     var x = prompt("Enter the first number:");
     var y = prompt("Enter the second number:");
     x = parseInt(x);
     y = parseInt(y);
     return [x, y];
}

function addition(){
    var [x, y] = getNumbers();   
    document.write(x + "+" + y + "=" + (x+y));
}