从一个函数中为不同的变量取两倍不同的值

时间:2014-02-27 09:26:35

标签: javascript html

我正在创建计算器,当我点击加号(+)运算符我将值放在全局变量中,我从输入字段获取并且我做空白输入字段,但我必须从输入中获取值,我进入第二次和我必须保留另一个变量。这是我想做的但我不明白该怎么做。

JS小提琴网址:http://jsfiddle.net/ravianexpert/9q6Xu/1

请帮帮我

var operation="";
var restValue="";
var lastValue="";

function operator(op){
    if(op == '+'){
        alert("Plus");
        restValue = Number(document.getElementById("display").value);
        document.getElementById("display").value="";
        if(restValue == ""){
            alert("Zero");
        }else{
            lastValue = Number(document.getElementById("display").value);
        }
        //document.getElementById("display").value=restValue + lastValue;
    }
    console.log("restValue : " + restValue);
    console.log("lastValue : " + lastValue);
    console.log("operation : " + operation);
    //lastValue = restValue.charAt(restValue.length - 1);
    //console.log(lastValue)
}

<div class="container">
    <div id="lastCalculation"></div>
    <input type="text" step="any" size="16" value="0" id="display" readonly />
    <div class="keypad">
        <span class="clear" onclick="reset()">C</span>
        <span class="del" onclick="deleteValue()">Del</span>
        <div class="clr"></div>
        <span onclick="setNum(7)">7</span>
        <span onclick="setNum(8)">8</span>
        <span onclick="setNum(9)">9</span>
        <span onclick="operator('/')">/</span>
        <span onclick="setNum(4)">4</span>
        <span onclick="setNum(5)">5</span>
        <span onclick="setNum(6)">6</span>
        <span onclick="operator('*')">*</span>
        <span onclick="setNum(1)">1</span>
        <span onclick="setNum(2)">2</span>
        <span onclick="setNum(3)">3</span>
        <span onclick="operator('-')">-</span>
        <span onclick="setNum(0)">0</span>
        <span onclick="setNum('.')">.</span>
        <span class="isEqualTo" onclick="calculate()">=</span>
        <span onclick="operator('+')">+</span>
        <div class="clr"></div>
    </div><!-- keypad -->
</div><!-- container -->

1 个答案:

答案 0 :(得分:1)

2016-05-29更新

进入一个伟大的answer by @yckart使用邪恶的eval()而使用Function构造函数,所以这里是一个演示如何能够做正确的计算。

document.querySelector('button').addEventListener('click', function (e) {

  var op = document.querySelector('input').value;        
  alert('Using new Function: ' + calculate(op) + '\nUsing eval(): ' + evil_eval(op));   // if default is used => 40.4
  
})

function calculate(op){
  return new Function('return ' + op)();
}

// added for test purpose, showing they return the same value
function evil_eval(op) {
  return eval(op);
}
<input type="text" value="12/5*9+9.4*2"> <button>Calc</button>

Src:Calculate string value in javascript, not using eval