Javascript 将运算符从字符串推入堆栈
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)
或正则表达式
我目前正在 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)
或正则表达式