Maison > Questions et réponses > le corps du texte
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)
过去多啦不再A梦2017-05-16 13:34:36
La raison est que chaque attribut d'obj utilisé pour le jugement a été calculé une fois, et un blocage conditionnel peut être ajouté pour l'améliorer :
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]))
}
Lorsqu'il y a peu de conditions à juger, vous pouvez utiliser plusieurs conditions trinoculaires pour juger. S'il y a trop de tels jugements, cette méthode d'écriture devrait être plus belle. Si vous ne pouvez pas l'accepter, vous devrez peut-être écrire autrement.
習慣沉默2017-05-16 13:34:36
L'erreur est qu'il n'y a pas d'enfants lorsque le premier est signalé
var convert = function(obj) {
return obj.map(o => ({
'number': 1,
'string': 's',
'array': o.children?convert(o.children):""//假设没有的时候返回空咯
}[o.type]))
}