【发布时间】:2020-10-29 13:12:14
【问题描述】:
我在这里有一个 sn-p 代码,其中我有一个数组,其中可能有也可能没有键。当用户按下“朋友”时,他们会将他们添加到列表(数组)中,在那里他们可能会开始与他们聊天(将 3 个朋友添加到数组中,然后开始聊天室)。选择的用户可能会被打开或关闭。
当前行为: 我可以添加/删除一个人,但我不能同时将多个人添加到数组中。当我添加一个人时,选择另一个人 - 第一个人是“活跃的”,当我删除第一个人时,第二个人会自动成为活跃
预期行为: 我希望能够将多个人添加到数组中,然后从数组中删除任何选定的项目
onFriendChatPress = (key) => {
console.log(key) // this is my key 'JFOFK7483JFNRW'
let friendsChat = this.state.friendsChat // this is an empty array initially []
if (friendsChat.length === 0) {
friendsChat.push(key)
} else {
// there are friends/keys in the array loop through all possible items in the array to determine if the key matches any of the keys
for (let i = 0; i < this.state.selGame.friends.length; i++) {
// if the key matches, 'toggle' them out of the array
if (friendsChat[i] === key) {
friendsChat = friendsChat.filter(function (a) { return a !== key })
}
else {
return friendsChat.indexOf(key) === -1 ? friendsChat.push(key) :
}
}
}
}
请帮忙!
【问题讨论】:
-
您已经尝试过什么,在哪里/为什么失败了?
-
@secan - 我确实陷入了循环/if/else 地狱,但下面的代码更优雅,但我仍然遇到同样的问题
标签: javascript arrays reactjs react-native logic