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.
2
Answers
Just one small change:
As NgDaddy already answered, all that was missing was to access the array within your function.
Just to add to the answer:
This in combination with
Math.floor
ensures thatMath.random() * array.length
is always between 0 andarray.length - 1
.