if语句中没有执行返回函数

时间:2017-04-01 22:10:46

标签: javascript string

嘿所以我正在编写一个函数来检查一系列大括号是否是有效序列。我有以下代码,它主要执行我想要它做的事情,除了它总是返回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

1 个答案:

答案 0 :(得分:0)

最后一次返回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
相关问题