gpt4 book ai didi

javascript - while 在 javascript 中一遍又一遍地循环

转载 作者:行者123 更新时间:2023-11-30 10:57:21 24 4
gpt4 key购买 nike

我正在编写考虑操作优先级的计算器代码。我想做的是替换匹配我写的正则表达式的优先级并计算它,并循环它直到字符串的长度,也就是最初的输入,变成1。

下面是我的代码,但运行它会导致无限循环。

const Calculator = function() {
this.evaluate = string => {
let regex = /\((\d+)\s[*/+-]\s(\d+)\)|(\d+)\s[*/]\s(\d+)|(\d+)\s[+-]\s(\d+)/g

while(string.length > 1) {
string.replace(regex, cal);
}
return string;
}
};

function cal(argument) {
let temp = argument.split(' ');
let regexP = /\((\d+)|(\d+)\)/g

if(temp[0].match(regexP)) {
temp[0] = temp[0].slice(1);
temp[2] = temp[2].slice(0, 1);
}
switch(temp[1]) {
case '+': return +temp[0] + +temp[2];
case '-': return +temp[0] - +temp[2];
case '*': return +temp[0] * +temp[2];
case '/': return +temp[0] / +temp[2];
default: return undefined;
}
}

let calculate = new Calculator()
console.log(calculate.evaluate("2 / 2 + 3 * 4 - 6"));

出于某种原因,代码一遍又一遍地循环并且没有返回值。

我做错了什么,我该如何解决?

最佳答案

你需要

(1)将调用.replace的结果赋值给字符串(Javascript字符串是不可变的):

string.replace(regex, cal);

(2) 结果字符串可能已完成所有 +-*/ 操作但仍具有大于 1 的长度,例如,如果结果为 3 * 4结果是 12。使用 while(/[-+*/]/.test(string)) { 代替:

const Calculator = function() {
this.evaluate = string => {
let regex = /\((\d+)\s[*/+-]\s(\d+)\)|(\d+)\s[*/]\s(\d+)|(\d+)\s[+-]\s(\d+)/g

while(/[-+*/]/.test(string)) {
string = string.replace(regex, cal);
}
return string;
}
};

function cal(argument) {
let temp = argument.split(' ');
let regexP = /\((\d+)|(\d+)\)/g

if(temp[0].match(regexP)) {
temp[0] = temp[0].slice(1);
temp[2] = temp[2].slice(0, 1);
}
switch(temp[1]) {
case '+': return +temp[0] + +temp[2];
case '-': return +temp[0] - +temp[2];
case '*': return +temp[0] * +temp[2];
case '/': return +temp[0] / +temp[2];
default: return undefined;
}
}

let calculate = new Calculator()
console.log(calculate.evaluate("2 / 2 + 3 * 4 - 6"));

您还可以通过一次性匹配和解构左侧数字、运算符和右侧数字来改进 cal 中的代码,使用

`const [, left, operator, right] = matchedSubstr.match(/(\d+) ([-+*/]) (\d+)/);

const Calculator = function() {
this.evaluate = string => {
let regex = /\((\d+)\s[*/+-]\s(\d+)\)|(\d+)\s[*/]\s(\d+)|(\d+)\s[+-]\s(\d+)/g

while(/[-+*/]/.test(string)) {
string = string.replace(regex, cal);
}
return string;
}
};

function cal(matchedSubstr) {
const [, left, operator, right] = matchedSubstr.match(/(\d+) ([-+*/]) (\d+)/);
switch(operator) {
case '+': return +left + +right;
case '-': return +left - right;
case '*': return +left * right;
case '/': return +left / right;
}
}

let calculate = new Calculator()
console.log(calculate.evaluate("2 / 2 + 3 * 4 - 6"));

关于javascript - while 在 javascript 中一遍又一遍地循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59467071/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com