繁体   English   中英

如何在 Javascript 中创建新的多对多引用?

[英]How to create a new many to many reference in Javascript?

想象一下,我有一个userother用户。 前者想跟随后者,这是我设计的多对多关系。 我怎样才能用 Javascript 做到这一点? 我需要类似user.followers.append(other)的东西。

在现实生活中,您为此使用数据库连接,并且您必须已经构建了一个后端。 但是如果你只是在 JS 中玩对象,那么你需要一个带有follow方法的User类。

function User (params) => {
  const {
    name,
    age,
    friends = []
  } = params

  this.name = name
  this.age = age
  this.friends = friends

  this.follow = (newFriend) => {
    this.friends.append(newFriend)
  }

  this.showFriends = () => {
    console.log(this.friends)
  }
}

然后创建两个用户。

const user = new User({
  name: "Joe",
  age: 25
})

const other = new User({
  name: "Francis",
  age: 27
})

然后你让一个家伙跟着另一个。

user.follow(other)

然后,您可以登录用户的朋友以查看发生了什么。

user.showFriends()

将 user.followers 设为数组。 这样您就可以推送试图关注他们的用户的用户 ID。

例如:

user = {'id': 'current_user_id',
        'followers' : ['user_id_1', 'user_id_2'....]
        };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM