I am trying to choose one person from my list in JS but whenever I check the out it give me all of them I think I have problem in array but I couldn't solve my problem.
Here is my code.
const names = ["Mary", "Anna", "Angel", "Nish", "Jack", "Pam"];
console.log(names); // shows all
function whosPaying(names) {
var numberOfPeople = names.length;
var randomPersonPosition = Math.floor(Math.random() * numberOfPeople);
var randomPerson = names[randomPersonPosition];
return randomPerson " is going to pay."
}
console.log(whosPaying(names))
CodePudding user response:
It looks like your code is almost correct, but you need to call the function to see the output. Try running console.log(whosPaying(names)) to see the randomly chosen person. Also make sure you are correctly calling the function with the list of names as an argument, if you are not passing the argument in the function call it will always return 'undefined is going to pay'
names = ["Mary", "Anna" ,"Angel", "Nish" , "Jack", "Pam"];
function whosPaying(names) {
var numberOfPeople = names.length;
var randomPersonPosition = Math.floor(Math.random() * numberOfPeople );
var randomPerson = names [randomPersonPosition];
return randomPerson " is going to pay.";
}
console.log(whosPaying(names));
This code defines an array of names, creates a function that selects a random person from the array, and then calls the function and logs the randomly chosen person to the console.
CodePudding user response:
You've got the answer in your original post... you just need to write the RESULT OF THE FUNCTION to the console, just like you did with the const random
... i.e.
names = ["Mary", "Anna" ,"Angel", "Nish" , "Jack", "Pam"];
function whosPaying(names) {
var numberOfPeople = names.length;
var randomPersonPosition = Math.floor(Math.random() * numberOfPeople );
var randomPerson = names [randomPersonPosition];
return randomPerson " is going to pay."
}
console.log(whosPaying(names));
THIS IS THE PART YOUR MISSING:
console.log(whosPaying(names));
CodePudding user response:
names = ["Mary", "Anna" ,"Angel", "Nish" , "Jack", "Pam"];
const random = Math.floor(Math.random() * names.length);
console.log(random, names[random]);
here is the souloution but I need to know if there is any way to solve it without const ?