JavaScript .push到空数组无效

时间:2017-10-04 12:00:41

标签: javascript arrays push

我试图解决有效的括号,并且如标题所述,我无法确定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;
&#13;
&#13;

如果console.logstack.push()之后,那么它会显示我刚刚插入的元素。但是当我在其他任何地方尝试它时,比如在else if语句内部或在return之前,似乎数组是空的。

1 个答案:

答案 0 :(得分:4)

以下是您的代码的更正版本

&#13;
&#13;
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;
&#13;
&#13;

return stack.length === 0;
一旦for循环结束,应该检查