TOP计算器:如何创建一个函数对字符串中的数字进行操作?


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title> Calculator </title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
<header>
<h1>Bria's Calculator</h1>
</header>
<div id="container">
<form name="calculate">
<input id="input" type="text" name="output" placeholder="0"><br/>
<input id="button1" type="button" value="1"/>
<input id="button2" type="button" value="2"/>
<input id="button3" type="button" value="3"/>
<input id="button/" type="button" value="/"/> <br/>
<input id="button4" type="button" value="4"/>
<input id="button5" type="button" value="5"/>
<input id="button6" type="button" value="6"/>
<input id="button*" type="button" value="*"/><br/>
<input id="button7" type="button" value="7"/>
<input id="button8" type="button" value="8"/>
<input id="button9" type="button" value="9"/>
<input id="button-" type="button" value="-"/><br/>
<input id="button(" type="button" value="("/>
<input id="button)" type="button" value=")"/>
<input id="button0" type="button" value="0"/>
<input id="button+" type="button" value="+"/><br/>
<input id="buttonc" type="button" value="c" style="background:red;"/>
<input id="button." type="button" value="."/>
<input id="button=" type="button" value="="/>
<input id="button%" type="button" value="%"/><br/>
</form>
</div>


<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
const input=document.getElementById("input");
const container=document.getElementById("container");
const calc =document.getElementById("button=");

container.addEventListener("click", function(e){
buttonClick(e.target.id);
});
//use event parameter of target to identify what's inside the id which are the buttons
calc.addEventListener("click", operate);
function buttonClick(buttonId){
if ((buttonId !="buttonc") && (buttonId !="button=")){
let button=document.getElementById(buttonId);
let tmp=buttonId;
tmp=tmp.replace("button", "");
entries(tmp);
}
};
//use 'replace' so when buttons are clicked it removes preface(button) and the id is just a number in the string format
function entries(tmp){
input.value += tmp; 
}
//concatenating values entered by pressing buttons within container
function operate (){
if(input.value=="."){
alert("Please enter a math equation");
} 
}
到目前为止,我已经能够将数字连接到字符串中,但现在我需要对它们进行实际操作。TOP不鼓励使用eval,所以我只是想知道如何设置一个函数来加,除,乘和减我在输入表单中调用的数字,而不使用eval()。我已经为上下文提供了HTML代码。

根据您期望的输入,您有几个选项可以将连接的字符串转换为数字。我推荐以下两种:

  1. parseFloat()-将带小数点的字符串转换为浮点数。

  2. parseInt(x,10)-将字符串的整数值转换为整数(不处理任何小数点)。注意第二个参数(10)。

最新更新