您的位置:首頁技術文章
文章詳情頁

javascript - 兩種遞歸的寫法,第一種為何報錯?

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

問題描述

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)

問題解答

回答1:

原因是判斷用的 obj 的每個屬性都被計算了一次,可以加條件阻塞改進:

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

當要判斷的條件少的時候可以用多個三目條件判斷,太多這樣的判斷,這種寫法要美觀一點,接受不了的可能只能寫 if else 了。

回答2:

因為你的遞歸沒有終止條件

回答3:

報錯是第一個的時候沒有children

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

標簽: JavaScript
国产综合久久一区二区三区