[英]Javascript pushing operators to a stack from a string
我目前正在用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;
}
}
如果只有(y ===(“ +” ||“-” ||“ *” ||“ /” ||“(” ||“)”)){}被推入堆棧。 我一直用來測試的字符串是“ 3 * 5 + 6”。 關於為什么會這樣的任何想法?
您的支票
y===("+" || "-" || "*" || "/" || "(" || ")"))
只是
y==="+"
您要么需要將其分解為
if (y==="+" || y==="-" || ...)
或者可以將indexOf與數組或字符串配合使用。
if (["+","-","*","/","(",")"].indexOf(y) > -1)
或正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.