简体   繁体   中英

JavaScript .push to an empty array not working

I'm trying to solve the Valid Parentheses, and as described in title, I can't figure how to Array.push to work in this context.

 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; } } 

If I console.log right after stack.push() , then it shows the element I just inserted. But when I try it anywhere else, like inside else if statements or before return , it seems like the array is empty.

Here is a corrected version of your code

 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('(())')); 

return stack.length === 0;

should be checked once the for loop is finished

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM