javascript - 如何创建这样的决策树?
解决方案
你可以拿一个带有想要的问题、答案和评论的对象。
function ask(question) {
if (!question) return;
var answer = prompt(question.question + '\n' + question.answers.map(({ answer }, i) => '\n' + i + ' ' + answer));
if (answer in question.answers) {
if (question.answers[answer].comment) {
alert(question.answers[answer].comment);
return;
}
ask(question.answers[answer]);
}
}
var tree = {
question: 'First of all, are you aged between 18 and 39 and a UK resident?',
answers: [
{
answer: 'Yes',
question: 'Great! Next, how are you planning to use your Lifetime ISA?',
answers: [
{
answer: 'I\'m buying my first (house)',
question: 'Is your first home going to cost less than £450,000?',
answers: [
{
answer: 'Yes',
question: 'And lastly, are you planning on buying your first home within the next five years?',
answers: [
{
answer: 'Yes',
comment: 'It looks like you could be eligible for a Lifetime ISA.'
},
{
answer: 'No',
comment: 'It looks like you could be eligible for a Lifetime ISA.'
}
]
},
{
answer: 'No',
comment: 'Based on the current government rules, Lifetime ISAs can be used to purchase homes costing £450,000 or less.'
}
]
},
{
answer: 'I\'m saving for my (...)',
question: 'What is your employment status?',
answers: [
{
answer: 'Employed',
comment: 'It looks like you could be eligible for a Lifetime ISA.'
},
{
answer: 'Self Employed',
comment: 'It looks like you could be eligible for a Lifetime ISA.'
},
{
answer: 'Not Employed',
comment: 'It looks like you could be eligible for a Lifetime ISA.'
}
]
}
]
},
{
answer: 'No',
comment: 'Our Lifetime ISAs are only available to UK residents aged between 18 and 39.'
}
]
},
question = tree;
ask(question);
推荐阅读
- excel - 标记和过滤重复 ListObject VBA
- c - 将两个文件合并到第三个文件会产生乱码
- linux - Linux 对以“|”分隔的文件进行排序 特点
- javascript - 在打字稿和nodejs中循环模型的所有属性
- magento2 - 插件类不存在
- spring-integration - 关于警告“调度程序没有订阅者”
- javascript - 如何在没有 CORB 警告的情况下检查 URL 是否存在?
- python - 如何将列表词转换为字典键并在末尾转换为字符串
- python - 如何循环里面有列表的字典?
- node.js - 我无法使用 discord.js 机器人 DM 用户