我有这个JavaScript程序,假设从用户输入做了非常简单的数学运算(2个数字,四个运算符之一 - +, - ,/,*)。问题是结果不稳定(可能不是最好的词,因为有一个模式,但在术语之前)并且我不知道为什么。
通过不稳定我的意思是,例如,如果你从总和5 + 5开始它会产生10,如预期的那样,但如果你用5 + 6做第二次尝试你会得到12,如果你尝试5 + 7结果将是14,依此类推......
有关为何会发生这种情况的任何想法?这是代码:
<HEAD>
<h2>A simple JavaScript powered calculator</h2>
<INPUT value="Enter a number" id="input1"></INPUT>
<SELECT id = "operator">
<option id="choose" >choose </option>
<option id="sum" value="+">sum</option>
<option id="subtraction" value="-">subtraction</option>
<option id="division" value="/">division</option>
<option id="multiplication" value="*">multiplication</option>
</SELECT>
<INPUT value="Enter a number" id="input2"></INPUT>
<INPUT value= "calculate" type="button" onclick=result()></INPUT>
<INPUT id="outputfield" type="text"></INPUT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
function sum(number, number) {return number + number};
function subtraction(number, number) {return number - number};
function division(number, number) {return number / number};
function multiplication(number, number) {return number * number};
function result(){if (document.getElementById("operator").value === document.getElementById("sum").value) {console.log("its a +!"), document.getElementById("outputfield").value =
sum(parseInt(document.getElementById("input1").value), parseInt(document.getElementById("input2").value));}
else if (document.getElementById("operator").value === document.getElementById("subtraction").value) {console.log("its a -!"), document.getElementById("outputfield").value =
subtraction(parseInt(document.getElementById("input1").value), parseInt(document.getElementById("input2").value));}
else if (document.getElementById("operator").value === document.getElementById("division").value) {console.log("its a /!"), document.getElementById("outputfield").value =
division(parseInt(document.getElementById("input1").value), parseInt(document.getElementById("input2").value));}
else if (document.getElementById("operator").value === document.getElementById("multiplication").value) {console.log("its a *!"), document.getElementById("outputfield").value =
multiplication(parseInt(document.getElementById("input1").value), parseInt(document.getElementById("input2").value));}
else if (document.getElementById("operator").value === document.getElementById("choose").value) {console.log("please choose an operator");}
}
</SCRIPT>
<p> </>
<p> April 2016 </p>
</BODY>
提前感谢任何提示
答案 0 :(得分:2)
您的功能,例如:
function sum(number, number) {return number + number};
在两个参数中使用相同的名称,即number
,当您尝试添加5和6时,名称number
被赋值为6
,而6 + 6 = 12
则为function sum(number1, number2) {return number1 + number2};
结果是对的。
请改为尝试:
<VideoList videos={this.props.channel.video_list}></VideoList>