javascript - 两种递归的写法,第一种为何报错?
本文介绍了javascript - 两种递归的写法,第一种为何报错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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)
解决方案
原因是判断用的 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 了。
这篇关于javascript - 两种递归的写法,第一种为何报错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文