请帮我修复此代码。对于上下文,我试图创建一个随机化器,它对用户输入的任何问题做出“是”或“否”等响应。主要问题是如何返回数组中的随机项?
let yesOrNo = ['DEFINITELY!', 'yes', 'of course', 'hell no', 'no', 'absolutely not', 'maybe', 'probably']
const randomiser = (ques) => {
if(typeof ques === 'string'){
return Math.floor(Math.random() * yesOrNo.length);
}
}
console.log(randomiser('should i accept the company offer?'));
//output: 6
我希望代码返回数组中写入的内容,但它返回数组项的索引号。例如,我希望它返回“也许”,而不是“6”。
我确实想出了另一种方法,但它非常混乱,而且看起来根本没有效率。
const num = Math.floor(Math.random() * 7);
const randomiser = (ques) => {
if(num === 0){
return 'DEFINITELY!'
} else if(num === 1){
return 'yes'
} else if(num === 2){
return 'of course'
} else if(num === 3){
return 'hell no'
} else if(num === 4){
return 'no'
} else if(num === 5){
return 'absolutely not'
} else if(num === 6){
return 'maybe'
} else if(num === 7){
return 'probably'
}
}
console.log(randomiser('should i accept the company offer?'));
//output: yes
如果它比我的更干净/更高效,我当然愿意接受实现随机化器的新方法。
只有一个小改变:
let yesOrNo = ['DEFINITELY!', 'yes', 'of course', 'hell no', 'no', 'absolutely not', 'maybe', 'probably'];
const randomiser = (ques) => {
if(typeof ques === 'string'){
return yesOrNo[Math.floor(Math.random() * yesOrNo.length)];
}
}
console.log(randomiser('should i accept the company offer?'));