[英]return function within if statement not executing
嘿,所以我正在编写一个函数,该函数检查一系列花括号是否为有效序列。 我有以下代码,除了可以始终返回false之外,它基本上可以完成我想要的工作。 如果我输入有效的括号序列,它将以正确的if语句结尾,但永远不会返回true。 我不明白为什么。
function match(s) { if (s === '(') { return ')' } else if (s === '[') { return ']' } else if (s === '{') { return '}' } } function open(b) { if ( (b === '(' ) || (b === '[' ) || (b === '{') ) { return true; } return false; } function checkValid(string, temp, n) { var current = string.charAt(n) var currentMatch = temp.charAt(0) if (!(current) && (n === string.length) && (temp === "")) { console.log('hey') return true } if (open(current)) { temp = match(current).concat(temp) checkValid(string, temp, n+1) } else { if (current === currentMatch) { temp = temp.substr(1) checkValid(string, temp, n+1) } return false; } return false; } function validBraces(braces) { var n = 0 var temp = '' return checkValid(braces, temp, n) } validBraces('()') // should return true validBraces('[[)}}{') //should return false
最后的false返回值总是从原始的checkValid函数调用中返回。
这是因为您没有返回递归的checkValid调用。
function match(s) {
if (s === '(') {
return ')'
}
else if (s === '[') {
return ']'
}
else if (s === '{') {
return '}'
}
}
function open(b) {
if ( (b === '(' ) || (b === '[' ) || (b === '{') ) {
return true;
}
return false;
}
function checkValid(string, temp, n) {
var current = string.charAt(n)
var currentMatch = temp.charAt(0)
if (!(current) && (n === string.length) && (temp === "")) {
console.log('hey')
return true
}
if (open(current)) {
temp = match(current).concat(temp)
return checkValid(string, temp, n+1)
}
else {
if (current === currentMatch) {
temp = temp.substr(1)
return checkValid(string, temp, n+1)
}
return false;
}
return false;
}
function validBraces(braces) {
var n = 0
var temp = ''
return checkValid(braces, temp, n)
}
validBraces('()') // should return true
validBraces('[[)}}{') //should return false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.