2 回答

TA貢獻1825條經(jīng)驗 獲得超6個贊
從高層次的角度來看,我會做如下:
有 2 個問題列表(針對 2 個年齡組)。
隨機播放相應(yīng)的一組問題
從問題集中彈出最后一個元素以顯示用戶。
重復(fù)。
好的,假設(shè)您有兩個問題列表或數(shù)組:
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'];
現(xiàn)在讓我們編寫一個小函數(shù)來打亂一個數(shù)組:
const shuffleArray = arr => arr
.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
現(xiàn)在一些偽代碼來顯示場景:
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條經(jīng)驗 獲得超5個贊
該命令let order = [...Array(numberOfItems).keys()].map(x => ({val:x,rand:Math.random()})).sort((a,b) => a.rand - b.rand).map(x => x.val);
將創(chuàng)建一個長度numberOfItems
很長的列表,但項目隨機排序。(項目將被 0 索引)。
例如,如果 numberOfItems = 10,這將給出一個類似的列表:[9, 5, 4, 1, 8, 3, 7, 6, 0, 2]
。
然后,您可以簡單地瀏覽此列表,以確定要問哪個問題而無需重復(fù)。
添加回答
舉報