1 回答

TA贡献1966条经验 获得超4个赞
你可以这样做:
const randomAnswers = {
goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'],
maybes: ['maybe','probably','perhaps',"honestly man, i really don't know this one"],
badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are you serious?']
};
const randomNumber = function(subject) {
return Math.floor(Math.random()*subject.length);
}
const types = Object.keys(randomAnswers);
const randomTypeNumber = randomNumber(types);
const randomType = types[randomTypeNumber];
const randomAnswerNumber = randomNumber(randomAnswers[randomType]);
const randomAnswer = randomAnswers[randomType][randomAnswerNumber];
console.log( { randomType, randomAnswer } );
您从对象中选择一个随机键,然后使用Object.keys(randomAnswers).length
随机数的数组长度从该数组中选择一个随机元素。
添加回答
举报