search

Home  >  Q&A  >  body text

javascript - Two ways of writing recursion, why does the first one report an error?

var obj = [
  { type: 'number' },
  { type: 'string' },
  { 
    type: 'array',
    children: [
      { type: 'number' },
      { type: 'string' }
    ]
  }
]

var convert = function(obj) {
  return obj.map(o => ({
    'number': 1,
    'string': 's',
    'array': convert(o.children)
  }[o.type]))
}

var convert2 = function(obj) {
  return obj.map(o => {
    if (o.type === 'number') {
      return 1
    } else if (o.type === 'string') {
      return 's'
    } else if (o.type === 'array') {
      return convert2(o.children)
    } else {
      return undefined
    }
  })
}

var converted = convert(obj)
var converted2 = convert2(obj)
阿神阿神2753 days ago527

reply all(3)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:34:36

    The reason is that each attribute of obj used for judgment has been calculated once, and conditional blocking can be added to improve it:

    var convert = function(obj) {
      return obj.map(o => ({
        'number': o.type === 'number ' && 1,
        'string': o.type === 'string ' &&  's',
        'array': o.type === 'array ' &&  convert(o.children)
      }[o.type]))
    }

    When there are few conditions to be judged, you can use multiple trinocular conditions to judge. If there are too many such judgments, this writing method should be more beautiful. If you cannot accept it, you may have to write if else.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:34:36

    Because your recursion has no termination condition

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-16 13:34:36

    The error is that there are no children when the first one is reported

    var convert = function(obj) {
      return obj.map(o => ({
        'number': 1,
        'string': 's',
        'array': o.children?convert(o.children):""//假设没有的时候返回空咯
      }[o.type]))
    }

    reply
    0
  • Cancelreply