简体   繁体   中英

Create array and randomize node.js array

I'm trying to write a cisco webex bot which get all people in the space(room) and randomly write only one name. I have this code

framework.hears("daily host", function (bot) {
  console.log("Choosing a daily host");
  responded = true;
  // Use the webex SDK to get the list of users in this space
  bot.webex.memberships.list({roomId: bot.room.id})
    .then((memberships) => {
      for (const member of memberships.items) {
        if (member.personId === bot.person.id) {
          // Skip myself!
          continue;
        }

        let names = (member.personDisplayName) ? member.personDisplayName : member.personEmail;
        let arrays = names.split('\n');
        var array = arrays[Math.floor(Math.random()*items.length)];
        console.log(array)
        bot.say(`Hello ${array}`);

       }
})
    .catch((e) => {
      console.error(`Call to sdk.memberships.get() failed: ${e.messages}`);
      bot.say('Hello everybody!');
    });
});

But this doesn't work. Also name after i use let arrays = names.split('\n'); separated by space and don't have comma. I think because of what code doesn't work Output of console log:

[ 'George Washington' ]

[ 'John' ]

[ 'William Howard Taft' ]

Main question now how to turn output to array?

That's because arrays[Math.floor(Math.random()*items.length)] only assigns an array with length 3. You need to randomise the index and push to array or use a sort function on the original array

 var array = arrays.sort((a,b)=>{
    return Math.floor(Math.random()*arrays.length);
 });

Here is how to get a single name from your data, and ensuring it is a string. There are only four names in the array, so run the snippet several times if you keep getting the same name.

 // A list of names. Notice that Arraymond is an array; the other names are strings. const names = [ 'George Washington', 'John', 'William Howard Taft', ['Arraymond'] ]; // Randomize the names const randomNames = names.sort(() => Math.random() - 0.5); // Get the first name. Make sure the name is a string (not an array) const name = randomNames[0].toString(); console.log(name)

A tip: don't name your array "array" or "arrays" - it is not meaningful. Use good naming conventions and meaningful variable names that help others understand what the code is doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM