【问题标题】:Javascript pushing operators to a stack from a stringJavascript将运算符从字符串推送到堆栈
【发布时间】:2015-01-29 18:52:59
【问题描述】:

我目前正在用 Javascript 编写一个程序,其中用户输入一个中缀表示法表达式作为字符串,然后将其转换为后缀表示法。我无法将每个运算符推入堆栈。以下是与我的问题相关的两个主要代码部分。

var input = readLine();
postfixCalc(input);

//main function that converts an infix notation function to postfix
function postfixCalc (input) {
  var operatorStack = new Stack();
  print("length of input: " + input.length);//DEBUG
  for (var i = 0; i < input.length; i++) {
    if (isOperator(input[i])) {
      operatorStack.push(input[i]);
      print("Pushing to stack: " + input[i]);//DEBUG
    } else {
      print("Not an operator: " + input[i]);//DEBUG
    }
    print("This is what the input character is: " + input[i]);//DEBUG
  }
}

//This function takes the current character being looked at in postfixCalc
//and returns true or false, depending on if the current character is 
//a valid operator
function isOperator(y) {
  //if y is a valid operator, return true.
  if (y===("+" || "-" || "*" || "/" || "(" || ")")) {
    print("What is being looked at: " + y);
    return true;
  } else {
    return false;
  }
}

仅比较此行中的第一个字符 if (y===("+" || "-" || "*" || "/" || "(" || ")")) { 从给定的字符串被推入堆栈。我用来测试的字符串是“3*5+6”。关于为什么会这样的任何想法?

【问题讨论】:

  • y===("+" || "-" || "*" || "/" || "(" || ")")) 不是你想的那样。

标签: javascript postfix-notation infix-notation


【解决方案1】:

你的支票

 y===("+" || "-" || "*" || "/" || "(" || ")"))

只是

y==="+"

您要么需要将其分解为

if (y==="+" || y==="-" || ...) 

或者您可以将 indexOf 与数组或字符串一起使用。

if (["+","-","*","/","(",")"].indexOf(y) > -1)

或正则表达式

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多