Javascript Array Splice without changing the index

前端 未结 5 1560
予麋鹿
予麋鹿 2020-12-17 14:20

I am working on a chat and using an array to hold the users. Here is my problem:

User1 joins and is given Index 0 in the array via push. User2 joins and is given Ind

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 15:11

    I'm sure there is a variety of solutions that work depending on your specific context. I have a project using React and was having a similar issue when setting an object in an array to undefined because elsewhere in the code I would get an error like cannot find {key} of undefined ...the same happened with null ...my solution that now works fine is to simply recreate the whole array, which I can do in my case because it is not a super long list. Altered to fit your description:

    let newUsers = [];
    users.forEach((u, i) => {
      if (u.isOnline) newUsers[i] = u;
    });
    this.setState({ users: newUsers });
    

    ...something to that effect. In my case I have a list of selected recipes. If the recipe was deleted from the overall list of recipes, this removes it from the list of selections, where the selected index indicates which 'course' it is (i.e. Appetizer, Entree, Dessert) so the index matters.

    Another solution could be to use your Users' ID as the index of the array. When a user comes online you can set onlineUsers[user.ID] = user //or true or user.Name or whatever

提交回复
热议问题