[英]JS calculator won't calculate double digits
我做了一個簡單的JavaScript計算器,它僅在使用一位數字時才有效。 但是,當您嘗試使用兩位數數字(例如12)時,它將不起作用。 例如,1 + 2 = 3但1 + 12 = 2,因為它僅計算輸入的前兩個數字。
我相信這是因為我設置了一個數組來收集所按的前兩個數字,然后對這兩個數字進行運算,如下面的代碼所示。 我怎樣才能解決這個問題?
var res = add(operands[0], operands[1]);
我的代碼: http : //jsfiddle.net/r8X9N/
我認為最簡單的方法 一種方法是將操作數保留為字符串,直到准備使用它們為止。
function subtract(a,b) {
return parseInt(a,10) - parseInt(b,10);
}
var operands = ["",""];
var operator;
$(".screen").text("");
$(".num").each(function() {
var selection = $(this).text();
$(this).click(function() {
$(".screen").append(selection);
if (operator) {
operands[1] = operands[1] + selection;
} else {
operands[0] = operands[0] + selection;
}
});
});
另一個選擇是根本不存儲操作數,而是獲取字符串的文本並進行評估(在您克服了使用eval的事實之后)
$(".screen").text("");
$(".num, .operator").each(function() {
var selection = $(this).text();
$(this).click(function() {
$(".screen").append(selection);
});
});
$(".equals").click(function() {
$(".screen").text(function(i,text){
return eval("(" + text + ")");
});
});
$(".clear").click(function() {
$(".screen").text("");
});
此版本的好處是,它現在支持多個運算符,並且可以在javascript中運行的任何運算符都沒有任何其他代碼(只是添加了一個錯誤捕獲。) http://jsfiddle.net/r8X9N/5/
您還可以將按下的數字存儲在數組中,並在按下運算符或等號時將它們合並。
var num = [];
$(".screen").text("");
$(".num").each(function() {
var selection = $(this).text();
$(this).click(function() {
$(".screen").append(selection);
num.push(parseInt(selection));
//operands.push(parseInt(selection));
});
});
$(".operator").each(function() {
var selection = $(this).text();
$(this).click(function() {
operator = selection;
operands.push(parseInt(num.join('')));
num = [];
$(".screen").append(operator);
});
});
$(".equals").click(function() {
operands.push(parseInt(num.join('')));
num = [];
switch (operator) {
case "+":
var res = add(operands[0], operands[1]);
$(".screen").text("").append(res);
operands = [];
operator = "";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.