繁体   English   中英

如何在 Javascript 中创建构造函数 class 的实例?

[英]How do I create instance of a constructor class in Javascript?

如果从构造函数实例创建的数组元素之一不具有相同的 email,我试图创建构造函数实例 function。

let users = [];
class User{
    constructor(email, name, age, lang){
         this.email = email;
         this.name = name;
         this.age = age;
         this.lang = lang
    }
    save(){
        users.push(this)
    }
}

function validate(email, name, age, lang){
    let uEmail = email;
    users.forEach(ele =>{
        if(ele.email == email){
            console.log('You have account with us')
        }else if(!ele.email){
          creatObj(uEmail, name, age, lang)
        }
     })

 }
function creatObj(email,name, age, lang){
    new User('s@s.com',name, age, lang).save()
}

当我使用相同的 email 运行代码时,我需要不将该实例推送到用户数组。 不幸的是,即使不满足条件,它也会继续推送实例。 如果用户具有唯一的电子邮件,我希望用户数组包含元素

任何人都可以帮忙吗?

最好使用键查找(例如小写的 email 地址)。 并使用适当的数据结构(例如 Object、Map、Set)来确保您不必搜索整个数组。

您的代码的最小修改版本:

 const usersByEmail = {}; class User{ constructor(email, name, age, lang){ this.email = email; this.name = name; this.age = age; this.lang = lang } save(){ usersByEmail[this.email.toLowerCase()] = this; } } function getOrCreateUser(email, name, age, lang){ if (email.toLowerCase() in usersByEmail) { console.log('You have account with us'); } else { new User(email,name, age, lang).save(); } return usersByEmail[email.toLowerCase()]; } getOrCreateUser('s@s.com', 'sam', 32, 'en'); getOrCreateUser('s@s.com', 'samuel', 23, 'es'); getOrCreateUser('a@b.com', 'other guy', 44, 'en'); getOrCreateUser('s@s.com', 'sam', 32, 'en'); console.warn('as object...'); console.log(usersByEmail); console.warn('as array...'); console.log(Object.values(usersByEmail));

暂无
暂无

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

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