please help me fix this code. For context, I was trying to create a randomiser that responds with 'yes' or 'no' etc to whatever question the user inputs. The main question is how do I return a random item in an array?
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
I want the code to return what's written in the array but instead it returns the index num of the array items. For example, instead of '6' I want it to return 'maybe'.
I did come up with another way but it's super messy and doesn't seem productive at all.
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
I'm certainly open to new methods of achieving a randomiser if it's more clean/efficient than mine.
Just one small change:
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?'));