javascript - Two ways of writing recursion, why does the first one report an error?
阿神
阿神 2017-05-16 13:32:36
0
3
523
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)
阿神
阿神

闭关修行中......

reply all(3)
过去多啦不再A梦

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.

曾经蜡笔没有小新

Because your recursion has no termination condition

習慣沉默

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]))
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template