需求:用js实现一个简单的计算器,可以计算包含+、-、*、/和()的字符串表达式实现:constparenthesisRegex=/(?<=(\((?.*?)))\)/;consthighPriorityRegex=/(?\d+)\s*?(?\*|\/)\s*?(?\d+)/constlowPriorityRegex=/(?\d+)\s*?(?\+|\-)\s*?(?\d+)/functioncalcCore(str:string){让匹配;//先匹配乘法和除法while((matches=str.match(highPriorityRegex))){const{0:{length},groups,index}=matches;const{n1,n2,operator}=组!constres=operator==='*'?(+n1*+n2):(+n1/+n2)str=str.slice(0,index!)+`${res}`+str.slice(index!+length)}//重新处理加法和减法while((matches=str.match(lowPriorityRegex))){const{0:{length},groups,index}=matches;const{n1,n2,operator}=组!constres=operator==='+'?(+n1++n2):(+n1-+n2)str=str。slice(0,index!)+`${res}`+str。slice(index!+length)}return+str}functioncalc(str:string){l等匹配;while((matches=str.match(parenthesisRegex))){const{index:rI,groups}=matchesconst{expression}=groups!;constlI=rI!-匹配[1].length;str=str.slice(0,lI)+`${calcCore(expression)}`+str.slice(rI!+1)}returncalcCore(str)}