계산기

<!doctype html>
<html>
<body>
<script>
var expression = prompt('계산식을 입력해 주세요');
var cursor = 0;
var lastCursorPosition = 0;
var tokens = [];
while(cursor < expression.length){
if(expression[cursor] == '+' || expression[cursor] == '-'){
tokens.push(expression.slice(lastCursorPosition, cursor));
tokens.push(expression[cursor]);

lastCursorPosition = cursor + 1;
}
cursor = cursor + 1;
}
tokens.push(expression.slice(lastCursorPosition, cursor));

var index = 0;
var sum = 0;
var operator = '+';

while(index < tokens.length){
if(tokens[index] == '+' || tokens[index] == '-'){
if(operator != ''){
if(operator == '+'){
sum = sum + Number(tokens[index-1]);
}else if(operator == '-'){
sum = sum - Number(tokens[index-1]);
}
}
operator = tokens[index];
}
index = index + 1;
}
if(operator == '+'){
sum = sum + Number(tokens[index - 1]);
} else {
sum = sum - Number(tokens[index - 1]);
}
console.log(sum);
</script>
</body>
</html>


'javascript' 카테고리의 다른 글

계산기 (3)  (0) 2017.09.04
계산기 (2)  (0) 2017.09.04
천 단위 쉼표 표시  (0) 2017.09.04
구구단 반복문  (0) 2017.09.04
최종 결과물 만들 목표  (0) 2017.08.28

+ Recent posts