JS - Discord Bot从数组中删除特定ID

时间:2018-03-18 00:07:40

标签: javascript discord

你好,有代码

$bot.on("presenceUpdate", (oldMember, newMember) => {
  if(oldMember.presence.status !== newMember.presence.status){
    const memberID = newMember.user.id;
    if(newMember.user.presence.status === "online"){      
      membersOnline.push(memberID);
      console.log("-------online--------");
      console.log(membersOnline);
    }else
    if(newMember.user.presence.status === "offline"){
      membersOnline.filter(e => e !== memberID)
      console.log("-------offline--------");
      console.log(membersOnline);
    }
      console.log(`${newMember.user.username} is now ${newMember.presence.status}`);

  }
});

Resoults是id不被删除。

  

-------离线-------- []

     

-l - RACE - l-现在离线

     

-------在线-------- [' 203287818330570752' ]

     

-l - RACE - l-现在在线

     

-------离线-------- [' 203287818330570752' ]

     

-l - RACE - l-现在离线

     

-------在线-------- [' 203287818330570752',' 203287818330570752' ]

     

-l - RACE - l-现在在线

DOCS

2 个答案:

答案 0 :(得分:1)

  

filter()方法创建一个包含所有传递元素的新数组   由提供的功能实现的测试。   https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

方法Array.prototype.filter()不会更改原始数组。如此简单的解决方案是:

membersOnline = membersOnline.filter(e => e !== memberID);

答案 1 :(得分:0)

我相信filter方法返回一个数组,因此在代码中运行方法但不将返回值赋给变量。请参阅下面的代码......

$bot.on("presenceUpdate", (oldMember, newMember) => {
    if(oldMember.presence.status !== newMember.presence.status){
      const memberID = newMember.user.id;
    }
    if(newMember.user.presence.status === "online"){      
        membersOnline.push(memberID);
        console.log("-------online--------");
        console.log(membersOnline);
    } else {
        if(newMember.user.presence.status === "offline"){
            var newOnlineMembers = membersOnline.filter(e => e !== memberID);  // add new variable for filtered array
            console.log("-------offline--------");
            console.log(newOnlineMembers); // output new variable
        }
        console.log(`${newMember.user.username} is now ${newMember.presence.status}`);
    }
});