【问题标题】:Creating an Object in JavaScript that does math calculations using values retrieved from a text box?在 JavaScript 中创建一个使用从文本框中检索到的值进行数学计算的对象?
【发布时间】:2012-10-14 21:44:35
【问题描述】:

我正在尝试使用 Objects 制作计算器。这里是 JSFiddle:http://jsfiddle.net/jNqEv/4/

我在制作计算器的其余部分时使用此代码来计算数字:

/*Computes the values inside the box and returns the answer.*/
function compute(form)  
{
    form.display.value = eval(form.display.value); 
}  

现在我需要创建一个执行计算的对象,而不是使用 JavaScript 预定义的对象 eval。我在想这样的事情:

基本上,这个对象从 id 为“输入”的文本框中获取值。这些值的形式为 2*3、1+2,5/7 等...所以我在想如果我拉字符串中的第二条数据使用 substr 然后我可以检查它是否是乘法、除法、减法或加法。

    function calc(arithmetic)
{
    this.arithmetic = arithmetic;
}        

var myCalc = new calc(input)
    {
    function maths (input) 
{
    var str = input;
    var a=str.substr(1,1); // example: 1+2   var a holds the 1
    var b=str.substr(2,1); //                var b holds the "+"
    var c=str.substr(3,1); //                var c holds the 2
                           // if the sign is equal to "+" add var a plus var b
                           // and then place them inside answerNumber.
                           // then take answerNumber and place its value
                           // inside the page element with the id "input"
    if(b == "+")
    {
        answerNumber = a + c;
    }
    else if(b == "-")
    {
        answerNumber = a + c;
    }
    else if(b == "*")
    {
        answerNumber = a * c;
    }
    else if(b == "/")
    {
        answerNumber = a / c;
    }
    document.getElementById("input").value=answerNumber;
        }


    }       

我尝试在各种网站上阅读有关 Objects 的信息,但它们根本没有帮助,以下是我去过的一些地方:“http://www.crockford.com/javascript/private.html” , "http://www.w3schools.com/js/js_objects.asp" 等等。对于我正在尝试做的事情,这些似乎不是很有用。也许你们中的一些人可以提供帮助。

这里是对象函数将被触发并放置到的按钮和文本框:

<input type="button" value="   =    " name="enter" onClick="compute(this.form)">
<input name="display"  id="input" size=25>

这是我的整个代码表,包括外部 JavaScript。

HTML:

<html> 
<head>
<title>Assignment 2</title>
</head>
<body>
<div align="center">
<span style="font-weight:bold" size="20">Calculator</span>
<br>
<!-- Prints my name -->
<form  name="MyName" id="form1" style="font-weight:bold" size="20">
<script>
document.write("Mallery, Cody");
</script>
</form>
<!-- Script -->
<script src="functions.js" type="text/javascript"></script>
<!-- The Calculator! -->
<center><form>
<table border=4>
<tr>
<td>
<input name="display"  id="input" size=25>
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="    7    " onClick="addChar(this.form.display, '7')">
<input type="button" value="    8    " onClick="addChar(this.form.display, '8')">
<input type="button" value="    9    " onClick="addChar(this.form.display, '9')">
<input type="button" value="    /    " onClick="addChar(this.form.display, '/')">
<br>

<input type="button" value="    4    " onClick="addChar(this.form.display, '4')">
<input type="button" value="    5    " onClick="addChar(this.form.display, '5')">
<input type="button" value="    6    " onClick="addChar(this.form.display, '6')">
<input type="button" value="    *    " onClick="addChar(this.form.display, '*')">
<br>

<input type="button" value="    1    " onClick="addChar(this.form.display, '1')">
<input type="button" value="    2    " onClick="addChar(this.form.display, '2')">
<input type="button" value="    3    " onClick="addChar(this.form.display, '3')">
<input type="button" value="    -    " onClick="addChar(this.form.display, '-')">
<br>

<input type="button" value="   0     " onClick="addChar(this.form.display, '0')">
<input type="button" value="    N    " onClick="changeSign(this.form.display)">
<input type="button" value="    +    " onClick="addChar(this.form.display, '+')">
<input type="button" value="   C   " onClick="this.form.display.value = 0 ">
<br>
<input type="button" value="   L    " name="L" onClick="Loop(this.form.display.value)" 
                                               title="If the L button is pressed, the digit present in the results box will be looped through and added up to the 'digit plus 10'.For example: After the calculator has been reset. The user can press the 1 button, then the L button 55 should be displayed in the calculator 1 + 10 = 11, therefore start with 1 and loop until less than 11 adding all of the numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55">
<input type="button" value="   =    " name="enter" onClick="compute(this.form)">
</td>
</tr>
</table>
<br>
<!-- Calculator User Guide -->
<span style="font-weight:bold" size="20">Instructions:</span>
<span size="16">
<br>Click a number, then an action, then another number, then the '=' button.
<br>Press 'C' when ready to start over. 
<br>The 'N' makes your previous number negative.
<br>The 'L' button requires one number to be avalible,
<br>It will loop through "that number" to "ten plus that number"
<br> and add all values and display.
<br>
<br>For example 1+2+3+4+5+6+7+8+9+10 = 55
</span>
<br><br>
<!-- Browser information -->
<span style="font-weight:bold" size="20">Navigator:</span>
<div id="Navigator"></div>

<script language="javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("Navigator").innerHTML=txt;

</script>
</form>           
</div>
</body>
</html>

外部 JavaScript:

/* gets the input from the keyboard OR clicking the button */
function addChar(input, character) 
{
if(input.value == null || input.value == "0")
    input.value = character;
else
    input.value += character;
}


/*changes the sign of the number inside the input box from negative to positive.*/
function changeSign(input) 
{
if(input.value.substring(0, 1) == "-")
    input.value = input.value.substring(1, input.value.length);
else
    input.value = "-" + input.value;
}


/*Computes the values inside the box and returns the answer.*/
function compute(form)  
{
    form.display.value = eval(form.display.value); /*The Calculator uses an Object for all calculations*/
}                


/* Loops the input by the value + 10 */
function Loop(input)
{
     var num = parseInt(input) + 10;
     var i=0;
     var sum=0;

    while(i < num)
        {
            sum=sum+i;
            i++;
        }
    document.getElementById("input").value=sum;

}

/*Compute Arithmetic*/
function calc() //creating an empty object named calc
{
}

var calc = new calc(); //creating a new instance of the calc object

calc.arithmetic = function maths (input) 
{
    var str = input;
    var a=str.substr(1,1); 
    var b=str.substr(2,1);
    var c=str.substr(3,1);

    if(b == "+")
    {
        answerNumber = a + c;
    }
    else if(b == "-")
    {
        answerNumber = a + c;
    }
    else if(b == "*")
    {
        answerNumber = a * c;
    }
    else if(b == "/")
    {
        answerNumber = a / c;
    }
    document.getElementById("input").value=answerNumber;
}

因此,感谢您指出正确方向的任何方式。

【问题讨论】:

  • 不要使用 eval()!!!看起来您正在使用用户输入的值。不要那样做。永远。
  • 我知道我需要创建一个对象来替换 Eval() 函数,这就是我的问题所在。我正在使用用户输入的值,因为这是一个计算器它将需要 1+2、3*4、5/6、3-2 等。我需要找到一种不使用 Eval 并创建自己的对象的方法。谢谢。
  • 我认为你把事情复杂化了太多......
  • 怎么样?这真的是我能想到的唯一方法。我只是无法为它编写代码,因为我没有经验。
  • @CodyMallery 您正在寻找类似Shunting-yard algorithm 的东西。

标签: javascript function object calculator


【解决方案1】:

我不知道你为什么认为你需要一个对象。只需将它们放在一个函数中 - 您已经拥有 maths 函数。它周围的代码只是一个语法错误。

通常,var myCalc = new calc(input); 创建calc 构造函数的实例 - 它后面不应跟随函数体。另外,通过做

function calc() {}
var calc = new calc();

你只是用它的实例覆盖calc 函数 - 很奇怪。

如果你想命名你的函数,即将它们作为属性放到一个对象上(这是一个好主意),你应该使用一个简单的Object 字面量。不需要会创建多个实例的构造函数,您只需要一个:

var calc = {
   arithmetic: function maths (input) { … }
};
// then call
calc.arithmetic("1+3");
// which sets the input field to "4"

【讨论】:

  • 嗯,我在这里需要一个对象的原因是因为它是一项任务,我必须按照指示去发球台,即使这意味着使用一些我会重新发明轮子的东西。谢谢你的信息!它有帮助。
  • 我想你可以说我这样做的原因是为了了解对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 2017-06-26
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
相关资源
最近更新 更多