我试图解决有效的括号,并且如标题所述,我无法确定Array.push
如何在此上下文中工作。
function isValidPar(par){
var stack = [];
var length = par.length;
for (var i=0; i<length; i++) {
var p = par[i];
if(p === "(" || p === "{" || p === "[") {
stack.push(p);
} else if(p === ")") {
if(stack.length === 0 || stack[stack.length-1] != "(") {return false}
stack.pop();
} else if(p === "]") {
if(stack.length === 0 || stack[stack.length-1] != "[") {return false}
stack.pop();
} else if(p === "}") {
if(stack.length === 0 || stack[stack.length-1] != "{") {return false}
stack.pop();
} return stack.length === 0;
}
}
&#13;
如果console.log
在stack.push()
之后,那么它会显示我刚刚插入的元素。但是当我在其他任何地方尝试它时,比如在else if
语句内部或在return
之前,似乎数组是空的。
答案 0 :(得分:4)
以下是您的代码的更正版本
function isValidPar(par){
var stack = [];
var length = par.length;
for (var i=0; i<length; i++) {
var p = par[i];
if(p === "(" || p === "{" || p === "[") {
stack.push(p);
} else if(p === ")") {
if(stack.length === 0 || stack[stack.length-1] != "(") {return false}
stack.pop();
} else if(p === "]") {
if(stack.length === 0 || stack[stack.length-1] != "[") {return false}
stack.pop();
} else if(p === "}") {
if(stack.length === 0 || stack[stack.length-1] != "{") {return false}
stack.pop();
}
}
return stack.length === 0;
}
console.log(isValidPar('(())'));
&#13;
return stack.length === 0;
一旦for循环结束,应该检查