2 回答
TA贡献1825条经验 获得超6个赞
从高层次的角度来看,我会做如下:
有 2 个问题列表(针对 2 个年龄组)。
随机播放相应的一组问题
从问题集中弹出最后一个元素以显示用户。
重复。
好的,假设您有两个问题列表或数组:
let smallQuestions = ['how many fingers do you have', 'what does the dog say', 'what color is a sheep', 'how old are you'];
let bigQuestions = ['how many kids do you have', 'did you do your taxes', 'do you own a car', 'do you drink alcohol'];
现在让我们编写一个小函数来打乱一个数组:
const shuffleArray = arr => arr
.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
现在一些伪代码来显示场景:
let smallQuestions = ['how many fingers do you have', 'what does the dog say', 'what color is a sheep', 'how old are you'];
let bigQuestions = ['how many kids do you have', 'did you do your taxes', 'do you own a car', 'do you drink alcohol'];
const shuffleArray = arr => arr
.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
const askMeSomething = (age) => {
if (age > 11) {
bigQuestions = shuffleArray(bigQuestions);
return bigQuestions.pop();
} else if (age >= 4) {
smallQuestions = shuffleArray(smallQuestions);
return smallQuestions.pop() || 'out of questions';
} else return 'too young';
}
console.log(askMeSomething(3));
console.log(askMeSomething(4));
console.log(askMeSomething(5));
console.log(askMeSomething(6));
console.log(askMeSomething(7));
console.log(askMeSomething(8));
TA贡献1772条经验 获得超5个赞
该命令let order = [...Array(numberOfItems).keys()].map(x => ({val:x,rand:Math.random()})).sort((a,b) => a.rand - b.rand).map(x => x.val);
将创建一个长度numberOfItems
很长的列表,但项目随机排序。(项目将被 0 索引)。
例如,如果 numberOfItems = 10,这将给出一个类似的列表:[9, 5, 4, 1, 8, 3, 7, 6, 0, 2]
。
然后,您可以简单地浏览此列表,以确定要问哪个问题而无需重复。
添加回答
举报