Javascript将操作符从字符串推送到堆栈

时间:2015-01-29 18:53:00

标签: javascript postfix-notation infix-notation

我目前正在用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”。有关为什么会这样的想法吗?

1 个答案:

答案 0 :(得分:1)

您的支票

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

只是

y==="+"

您需要将其分解为

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

或者您可以将indexOf与数组或sting一起使用。

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

或正则表达式