首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建数组和随机化node.js数组

创建数组和随机化node.js数组
EN

Stack Overflow用户
提问于 2021-11-23 14:17:54
回答 2查看 79关注 0票数 0

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

代码语言:javascript
复制
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');后命名,用空格分隔,没有逗号。我认为是因为什么代码不能工作,控制台日志的输出:

“乔治·华盛顿”

“约翰”

“威廉·霍华德·塔夫脱”

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

EN

回答 2

Stack Overflow用户

发布于 2021-11-23 15:12:17

这是因为arraysMath.floor(Math.random()*items.length)只分配长度为3的数组。您需要将索引随机化并推入数组,或者对原始数组使用排序函数

代码语言:javascript
复制
 var array = arrays.sort((a,b)=>{
    return Math.floor(Math.random()*arrays.length);
 });

如果您希望根据您的问题获得输出,则可以使用reduce而不是sort。

代码语言:javascript
复制
var arrays = [ 'George Washington', 'John',  'William Howard Taft'];
var array = arrays.reduce((a,i)=>{
    if(!a) a = [];
        a.splice(Math.floor(Math.random()*arrays.length), 0, [i]);
    return a;
 },[]);
票数 0
EN

Stack Overflow用户

发布于 2021-11-25 07:51:38

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

代码语言:javascript
复制
// 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“或”array“--这是没有意义的。使用良好的命名约定和有意义的变量名来帮助其他人理解代码的作用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70082498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档