search

Home  >  Q&A  >  body text

How to randomly select a name in an array list

I encountered a problem about an array list. I wanted to return a random name in the array list, but I encountered a problem when implementing it.

``function randomName(names) {
names = ["john", "Ben", "Jenny", "Michael", "Chloe"];
Math.random(names.length);
console.log(names);

    return names + "is going to buy lunch today!";

}

randomName();

I want the output to be:

Michael (or any name in the array) is going to buy lunch today!

Can you guide me on how to achieve this?


P粉418351692P粉418351692526 days ago604

reply all(1)I'll reply

  • P粉455093123

    P粉4550931232023-07-20 00:21:31

    const index = Math.floor(Math.random() * names.length);
    
    names[index]

    reply
    0
  • Cancelreply