[英]How to parse a simple arithmetic operation with regex in javascript?
我正在使用 AngularJS 制作主頁,並且有算術 function。
<div class="input-form">
<input ng-model="value1" id="value1" type="number" />
<input ng-model="value2" id="value2" type="number" />
<input ng-model="value3" id="value3" type="number" />
<input ng-model="value4" id="value4" type="number" />
<input ng-model="value5" id="value5" type="number" />
</div>
<div class="equation-form">
<input ng-model="equation" type="text" />
</div>
<button class="yellow" ng-click="calculate()">Calculation</button>
如果用戶在方程字段輸入算術方程后按下“計算”按鈕,需要計算結果並發送服務器。
方程輸入如"1 + 2 - 3 * 4 + 5"
。
1,2,3,4,5 值表示輸入值命名為 value1, value2, value3, value4, value5
這是我試圖實現的計算:
scope.calculate = function () {
let equation = scope.equation.replace(/\s+/g, ''); // remove spaces
if (!/^\d+(?:[+-]\d+)*$/.test(expression)) { //
console.error('wrong equation');
return;
}
let fieldIndexes = expression.split(/(?=[+-])/); // split expression
if (fieldIndexes) {
fieldIndexes.forEach(x => {
// process calculation
});
}
}
Function 分兩步完成:
首先,將方程拆分為 [ 1, +2, -3, *4, 5 ]。
其次,計算分裂方程。
但現在,我只用“-”、“+”分開。 如果用戶輸入"1 + 2 - 3 + 4 - 5"
,當前 function 將其拆分為"1", "+2", "-3", "+4", "-5"
。
如何用“-”、“+”、“*”、“/”符號分割字符串?
有什么建議么?
好吧,我寫了一些不使用 RegExp 的東西。
class Operation {
constructor(data) {
this.data = data;
}
result(items = null) {
for (var i = 0; i < items.length; i++) {
items[i] = items[i].split(this.data.op);
if (this.data.next) {
items[i] = this.data.next.result(items[i]);
}
items[i] = items[i].reduce(this.data.reducer);
}
return items;
}
}
function calculate(expr) {
var mult = new Operation({ op: "*", next: null, reducer: (f, l) => { return parseInt(f) * parseInt(l) } });
var div = new Operation({ op: "/", next: mult, reducer: (f, l) => { return parseInt(f) / parseInt(l) } });
var sub = new Operation({ op: "-", next: div, reducer: (f, l) => { return parseInt(f) - parseInt(l) } });
var add = new Operation({ op: "+", next: sub, reducer: (f, l) => { return parseInt(f) + parseInt(l) } });
return add.result([expr.replace(/\s+/g, "")])[0];
}
您為計算 function 提供算術表達式,它會為您返回結果。 每個操作層將操作數 - “項目” - 傳遞給下一個更高階的操作,直到它到達最后一個(這里是乘法)。
示例:console.log(calculate("6 * 5 - 2"));
現在添加括號應該很簡單。
這有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.