我一直在尝试创建一个小费计算器,用户输入他们的餐价。然后点击计算按钮。我想让我的应用程序回馈的是15%的小费和总额,这是原始的膳食价格加上添加的小费。我似乎无法让我的功能正常工作,我无法找到任何关于这个的东西,因为它全部是在java和其他编码语言。我不确定我是否过度复杂功能或只是缺少小事。感谢您的反馈!
指数:
<div>
Enter Total Cost <input id = "numbers" />
<br/><br/>
Tip Amount: <p id = "tip"/></p>
Total + Tip: <p id = "total"/></p>
<input value = "Calculate" onclick="calculate()" type = "button"/>
</div>
<script src ="src/main.js"></script>
</body>
</html>
Typecript:
var numberInput:HTMLInputElement = <HTMLInputElement>document.getElementById("numbers");
var numbertip:HTMLElement = <HTMLInputElement>document.getElementById("tip");
var numbertotal: HTMLElement = <HTMLInputElement>document.getElementById("total");
function calculate() {
var numberinputString:String = numberInput.value.toString();
var stringarray:string[] = numberinputString();
var numberAarray:number[]=[];
for(var i=0; i<stringarray.length ; i++)
{
numberAarray[i]= parseFloat(stringarray[i]);
}
var tip:number=0;
var total:number=0;
for (var i =0; i< numberAarray.length ;i++){
total= total+ numberAarray[i];
}
numbertip.innerHTML=tip.toString();
numbertotal.innerHTML=total.toString();
}
答案 0 :(得分:0)
如果您担心过度复杂的功能,这是一个更简单的实现,可以达到预期的效果:
var numberInput: HTMLInputElement = <HTMLInputElement>document.getElementById("numbers");
var numbertip: HTMLElement = <HTMLInputElement>document.getElementById("tip");
var numbertotal: HTMLElement = <HTMLInputElement>document.getElementById("total");
function calculate() {
var numberinputString: string = numberInput.value;
var cost: number = parseFloat(numberinputString);
var tip: number = cost * .15;
var total: number = cost + tip;
numbertip.innerHTML = tip.toString();
numbertotal.innerHTML = total.toString();
}
但是,Typescript非常擅长类型推断,甚至可以进一步简化:
var numberInput: HTMLInputElement = <HTMLInputElement>document.getElementById("numbers");
var numbertip = document.getElementById("tip");
var numbertotal = document.getElementById("total");
function calculate() {
var numberinputString = numberInput.value;
var cost = parseFloat(numberinputString);
var tip = cost * .15;
var total = cost + tip;
numbertip.innerHTML = tip.toString();
numbertotal.innerHTML = total.toString();
}