繁体   English   中英

Javascript:如何在条件中使用运算符**

[英]Javascript: how to use the operator ** in a conditional

我想在字符串中找到一个运算符,例如"3+7" ,识别运算符并求和。 我对运算符+ - * /但对**没有这样的代码,我的代码返回我的 boolean。

我想知道为什么会发生这种情况以及如何使用具有条件的指数运算符。

// To know if the string have a "+", "-", "*", "**" or "/" inside of him
let foundCharacterFunction = function(str, char) {
 for(var i = 0; i < str.length; i++) {
   if (str[i] == char) {
     return char;
   } 
 }
 return false;
};


// With this we can use the specific character founded
let characterFoundAlready = foundCharacterFunction("3+7", "+");


// "characterFoundAlready" always is a string but work with all, less with exponential operator
console.log(typeof characterFoundAlready);


// To know what we going to do if we have one character or other
let enterTheCondition = 
 (characterFoundAlready === "+" ) ? console.log("We going to sum!") :
 (characterFoundAlready === "-" ) ? console.log("We going to rest!") :
 (characterFoundAlready === "*" ) ? console.log("We going to multiply!") :
 (characterFoundAlready === "**" ) ? console.log("We going to power!!") :
 (characterFoundAlready === "/" ) ? console.log("We going to divide!") :
 console.log("That character it can't be procesed");

提前感谢您的时间和关注。

我建议您阅读有关Reverse Polish notation Algo 操作命令,而不是字符并允许处理不同优先级的操作。 你也应该这样做。

编辑:

这是一些如何处理它的小例子:

const opertaionDescriptions = [
  { operation: '+', message: 'We going to sum!' },
  { operation: '-', message: 'We going to rest!' },
  { operation: '*', message: 'We going to multiply!' },
  { operation: '**', message: 'We going to power!' },
  { operation: '/', message: 'We going to divide!' },
];

let foundCharacterFunction = function (str) {
  const found = str.match(/[\d\s]([+*/-]+)[\s\d]/i);
  if (found && found[1]) {
    return found[1];
  }

  return false;
};

// With this we can use the specific character founded
let characterFoundAlready = foundCharacterFunction("3+7");

// To know what we going to do if we have one character or other
console.log(
  (opertaionDescriptions.find(({operation}) => operation === characterFoundAlready) 
    || { message: "That character it can't be procesed"})
  .message
); 

// With this we can use the specific character founded
characterFoundAlready = foundCharacterFunction("3 ** 7");

// To know what we going to do if we have one character or other
console.log(
  (opertaionDescriptions.find(({operation}) => operation === characterFoundAlready) 
    || { message: "That character it can't be procesed"})
  .message
); 

当然,您仍然可以通过手动创建 Regexp 来定义精确的搜索操作,例如/[\d\s](char_or_string_to_search)[\s\d]/i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM