javascript - 兩種遞歸的寫(xiě)法,第一種為何報(bào)錯(cuò)?
問(wèn)題描述
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)
問(wèn)題解答
回答1:原因是判斷用的 obj 的每個(gè)屬性都被計(jì)算了一次,可以加條件阻塞改進(jìn):
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]))}
當(dāng)要判斷的條件少的時(shí)候可以用多個(gè)三目條件判斷,太多這樣的判斷,這種寫(xiě)法要美觀一點(diǎn),接受不了的可能只能寫(xiě) if else 了。
回答2:因?yàn)槟愕倪f歸沒(méi)有終止條件
回答3:報(bào)錯(cuò)是第一個(gè)的時(shí)候沒(méi)有children
var convert = function(obj) { return obj.map(o => ({ ’number’: 1, ’string’: ’s’, ’array’: o.children?convert(o.children):''//假設(shè)沒(méi)有的時(shí)候返回空咯 }[o.type]))}
