我的Javascript后缀中缀代码正在破坏JSFIDLE-为什么?

我的Javascript后缀中缀代码正在破坏JSFIDLE-为什么?,javascript,jsfiddle,Javascript,Jsfiddle,这是代码,我在HTML部分的所有内容都是 选项为onDomready和jQuery 1.9.1 var operators = '+-*/()'; Array.prototype.peek = function () { return this[this.length - 1]; }; function isDigit(c) { return !isOperator(c); } function isOperator(c) { return operators.in

这是代码,我在HTML部分的所有内容都是

选项为onDomreadyjQuery 1.9.1

var operators = '+-*/()';

Array.prototype.peek = function () {
    return this[this.length - 1];
};

function isDigit(c) {
    return !isOperator(c);
}

function isOperator(c) {
    return operators.indexOf(c) >= 0;
}

function operatorPriority(operator) {
    return operator === '*' || operator === '/' ? 1 : 0;
}

function comparePriority(a, b) {
    return operatorPriority(a) >= operatorPriority(b);
}

function toPostfix(infix) {
    var stack = [];
    stack.push('(');
    infix += ')';

    var count = 0;
    var postfix = "";

    while (stack.length > 0) {
        var c = infix.charAt(count++);
        if (isDigit(c)) {
            postfix += c;
        } else if (c === '(') {
            stack.push(c);
        } else if (isOperator(c)) {
            while (isOperator(stack.peek())) {
                if (comparePriority(stack.peek(), c)) {
                    postfix += stack.pop();
                } else {
                    break;
                }
            }
            stack.push(c);
        } else { // assumed )
            while (stack.peek() !== '(') {
                postfix += stack.pop();
            }
            stack.pop();
        }
    }
    return postfix;
}

var infix = "2+4+5";
$('p').text(toPostfix(infix));

在while循环中,必须在
计数上添加一个条件:

while (stack.length > 0 && count <= infix.length) {
    ...
}

while(stack.length>0&&count)你有没有看到堆栈是如何变化的,以及它是否变为空的?我不能,因为它实际上只是破坏了JSFIDLE-它冻结了。试试看?好吧,在设置了断点后启动它。这个方法可能会派上用场。