到变量名JS的字符串



我试图创建一个网站,如果你输入信息,它使对象用户。但我不知道如何给每个对象取不同的名字。有没有一种方法可以从字符串创建一个变量名?

function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.friends = 0,
this.friendnames = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
//I  want name to be what the user enters instead of name.
name = new user(username,name)
};

我该怎么办?

我的意思是你可以创建用户对象并以以下方式使用它:

let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.friends = 0,
this.friendnames = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
newuser('name1', 'name1@mail.com', 'username1');
console.log(users['name1'].listuser());

最新更新