繁体   English   中英

创建数组并随机化 node.js 数组

[英]Create array and randomize node.js array

我正在尝试编写一个cisco webex机器人,它可以让所有人进入空间(房间)并随机只写一个名字。 我有这个代码

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!');
    });
});

但这不起作用。 在我使用之后命名为let arrays = names.split('\n'); 用空格隔开,没有逗号。 我认为由于控制台日志的哪些代码不起作用 Output :

[ '乔治华盛顿' ]

[ '约翰' ]

['威廉霍华德塔夫脱']

现在的主要问题是如何将 output 转换为数组?

这是因为 arrays[Math.floor(Math.random()*items.length)] 只分配长度为 3 的数组。您需要随机化索引并推送到数组或在原始数组上使用排序 function

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

以下是如何从您的数据中获取单个名称,并确保它是一个字符串。 数组中只有四个名称,因此如果您始终获得相同的名称,请多次运行该代码段。

 // 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)

提示:不要将您的数组命名为“array”或“arrays”——这没有意义。 使用良好的命名约定和有意义的变量名,以帮助其他人理解代码在做什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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