成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

javascript - 兩種遞歸的寫(xiě)法,第一種為何報(bào)錯(cuò)?

瀏覽:104日期:2023-09-20 14:49:16

問(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]))}

標(biāo)簽: JavaScript