【问题标题】:How to create one array from multiple output node.js如何从多个输出 node.js 创建一个数组
【发布时间】:2022-01-06 23:55:13
【问题描述】:

我有这个代码

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;                                                                 
bot.say(`Hello ${member.personDisplayName`);

逐行产生多个输出 像这样:

杜约翰

阿尔弗雷德·彭尼沃尔

米歇尔·李

我需要从这个输出创建一个数组,随机化这个数组,机器人必须从数组中只说出一个随机名称。 请注意名称的数量可能不同

PS 我尝试使用 split 但得到 3 个不同的数组而不是一个。

【问题讨论】:

    标签: javascript node.js arrays


    【解决方案1】:

    首先,在 question 中解释了从数组中获取随机元素。

    只显示一个随机元素,这不是你自己的名字,那么这应该适合你。既然memberships.items已经是一个数组,那么我们可以直接从中抽取一个随机元素。

    示例代码:

    bot.webex.memberships.list({roomId: bot.room.id})
    .then((memberships) => {
    
    
      let member
      // take random member and repeat until it's not the current user.
      do {
      
        const items = memberships.items
    
        // get random element
        // https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array/5915122#5915122
        member = items[Math.floor(Math.random()*items.length)];
    
      } while(member.personId === bot.person.id);
    
    bot.say(`Hello ${member.personDisplayName}`)
    
    })
    
    

    【讨论】:

    • 你好@Silvan Bregy!谢谢!它的作品!)
    【解决方案2】:

    您可以filter 找出不是您的成员,然后map 在该对象数组上创建名称列表。然后从该数组中选择一个随机名称。

    bot
      .webex
      .memberships
      .list({roomId: bot.room.id})
      .then(logRandomName);
    

    这是一个基于您的代码的工作示例。

    const bot = { person: { id: 4, name: 'Joe' } };
    const memberships=[{personId:1,name:"Fozzie Bear"},{personId:2,name:"Carlos The Jackal"},{personId:3,name:"Bob From Accounting"},{personId:4,name:"Joe"},{personId:5,name:"Gunther"},{personId:6,name:"Ali"},{personId:7,name:"Renaldo"}];
    
    function logRandomName(memberships) {
    
      // First `filter` over the memberships array to
      // to produce a new array that doesn't contain the
      // member object that matches the bot.person.id
      const names = memberships.filter(member => {
        return member.personId !== bot.person.id;
    
      // And then `map` over that array to return an
      // array of names
      }).map(member => member.name);
    
      const rnd = Math.floor(Math.random() * names.length);
    
      // Then pick a random name from the names array
      console.log(`Hallo ${names[rnd]}`);
    
    }
    
    logRandomName(memberships);

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 2010-11-28
      • 2023-01-04
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      相关资源
      最近更新 更多