2

我真的很驚訝於一個問題。將前綴表達式轉換爲使用javaScript的中綴表達式

轉換使用JavaScript

[ 「和」 下面的表達式,[ 「<」, 「VAR1」, 「VAR2」],[ 「OR」,[ 「>」, 「VAR3」,「 VAR4 「],[」 ==」, 「VAR5」, 「var6」]]

VAR1 < val2的AND(VAR3> VAL4 OR val5 == VAL6)

遺憾的是,我沒有任何更多的信息

+0

嗨,你有沒有得到答案? –

回答

0

試試這個..

function rpn(input) { 
    var ar = input.split(/\s+/), st = [], token; 
    while(token = ar.shift()) { 
    if (token == +token) { 
     st.push(token); 
    } else { 
     var n2 = st.pop(), n1 = st.pop(); 
     var re = /^[\+\-\/\*\>\<\==\.]$/; 
     if(n1 != +n1 || n2 != +n2 || !re.test(token)) { 
      throw new Error('Invalid expression: ' + input); 
     } 
     st.push(eval(n1 + token + ' ' + n2)); 
    } 
    } 
    if(st.length !== 1) { 
     throw new Error('Invalid expression: ' + input); 
    } 
    return st.pop(); 
} 
0

你可以試試下面的語法:

if ((var1 < var2) AND (var3 > var4 OR var5==var6)) 
0

嘗試用這種下文提到的算法

1. Accept a prefix string from the user. 

2. Start scanning the string from right one character at a time. 

3. If it is an operand, push it in stack. 

4. If it is an operator, pop opnd1, opnd2 and concatenate them in the order (opnd1, optr, opnd2). 

5. Push the result in the stack. 

6. Repeat these steps until arr of input prefix string ends. 

7. Pop the remaining element of the stack, which is the required Infix notation equivalent to a given Prefix notation. 
2

試試這個遞歸方法

var convert = function(arr) { 
    if (typeof arr[0] == 'string' && arr[1] instanceof Array && arr[2] instanceof Array) { 
     return ' (' + convert(arr[1]) + arr[0] + convert(arr[2]) + ') '; 
    } else { 
     return ' ' + arr[1] + ' ' + arr[0] + ' ' + arr[2] + ' '; 
    } 
} 
+0

這應該是被接受的答案 –