我試圖將計算字符串轉換爲JavaScript中的Number對象,但是我找不到執行想要的工作的函數。Javascript,完全計算爲數
parseInt(String)
函數只解析計算的第一個數字,但不對其應用數學函數。
我的什麼,我的意思是這樣的最低版本:https://jsfiddle.net/qd7u6h60/3/
我會很高興,如果有人有anwser
我試圖將計算字符串轉換爲JavaScript中的Number對象,但是我找不到執行想要的工作的函數。Javascript,完全計算爲數
parseInt(String)
函數只解析計算的第一個數字,但不對其應用數學函數。
我的什麼,我的意思是這樣的最低版本:https://jsfiddle.net/qd7u6h60/3/
我會很高興,如果有人有anwser
alert(eval("12+13+5/5"))
那是什麼EVAL是爲了。 Eval分析有效的js,而數學運算是有效的JS。請注意以下內容
4^4 => is the binary XOR operator
//you want
4**4
您需要使用eval()或parseInt。 更新小提琴:https://jsfiddle.net/qd7u6h60/5/
$('button[name=calculate]').click(function() {
var calculation = $('input[name=calculation]').val();
var result = eval(calculation); /* Only parse the first number of the complete calculation */
$('input[name=result]').val(result);
});
感謝它的工作,然後我把我的問題作爲重複,因爲我看到問題已經被問到。 – Xisabla
您可以使用eval()來計算值。 eval()函數評估以字符串表示的JavaScript代碼。 eval()函數的參數是一個字符串。如果字符串表示表達式,則eval()將計算表達式
請查找下面的代碼片段。我已經修改了你的榜樣
$('button[name=calculate]').click(function() {
var calculation = $('input[name=calculation]').val();
var result = eval(calculation); /* Only parse the first number of the complete calculation */
$('input[name=result]').val(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<br/>
<div class="input-group">
<input type="text" name="calculation" class="form-control" placeholder="Calculation, eg: (5 - 2)/(7 + 4)">
</div>
<br/>
<div class="input-group">
<span class="input-group-addon">=</span>
<input type="number" name="result" class="form-control" placeholder="Result" readonly>
</div>
<br/><br/>
<button type="button" name="calculate" class="btn btn-info">Calculate !</button>
</div>
發表[MCVE] **在你的問題**請。 – j08691