I'm learning Switch in JS. I created an array of names and I made a click event to pick a random name but it works only once. Another clicks repeats the same choice again and again. The random() function doesn't seem to work. How to do it in vanilla JS in a simple way? Can anyone explain it to a learner using only basic methods?
<button id="chooseRandom" onclick="checkPerson()">Choose</button>
const people = ["Harriet", "Steve", "Ana", "Jessica", "Jacob", "Don"];
let randomPerson = people[Math.floor(Math.random() * people.length)];
let btn = document.querySelector("#chooseRandom")
function checkPerson () {
switch(randomPerson) {
case randomPerson = "Ana":
console.log("Hi, Ana.");
break;
case randomPerson = "Jessica":
console.log("Hi, Jessica.");
break;
case randomPerson = "Harriet":
console.log("Hi, Harriet.");
break;
default:
console.log("I'm not interested in men.");
}
}
CodePudding user response:
You need a new random people every time the checkPerson is called. So, you need calculate it inside of the function.
const people = ["Harriet", "Steve", "Ana", "Jessica", "Jacob", "Don"];
let btn = document.querySelector("#chooseRandom")
function checkPerson () {
const randomPerson = people[Math.floor(Math.random() * people.length)];
switch(randomPerson) {
case randomPerson = "Ana":
console.log("Hi, Ana.");
break;
case randomPerson = "Jessica":
console.log("Hi, Jessica.");
break;
case randomPerson = "Harriet":
console.log("Hi, Harriet.");
break;
default:
console.log("I'm not interested in men.");
}
}
CodePudding user response:
You assign a value to randomPerson
only once. Move it to checkPerson ()
CodePudding user response:
const people = ['Harriet','Steve','Ana','Jessica','Jacod','Don' ];
function checkPerson(){
const num = Math.floor(Math.random() * people.length);
console.log(`Hi, ${people[num]}.`);
}