存储对通讯簿应用的实例化对象的引用

Storing references to instantiated objects for an address book app

本文关键字:实例化 对象 引用 应用 存储      更新时间:2023-09-26

我正在尝试学习如何编程,但我被困在Codecademy等人没有阐明的东西上。它们总是教您如何将名称硬编码到实例化的对象,以便您以后可以引用它们。我需要知道如何处理动态联系人列表。

我想知道如何智能地存储对我正在创建的对象的引用,以便我可以知道实例化的对象将来的位置。

例如,如果下面的这个应用程序代表了某个地址簿应用程序的开始,我将如何将用户在 DOM 中的输入连接到 Javascript 中的实际对象?我的意思不是解释如何使用事件侦听器,而是我可以使用哪些数据将浏览器中的某个联系人链接到数据数组中的某个联系人。

目前,我

只是将所有内容推送到一个数组中,但我不确定我应该使用什么作为标识符。当然有数组的索引,但是如果我事先不知道 json 数据列表中的联系人,我怎么知道 [0] 是 Ethan,而不是可能在某个时候添加到 json 列表中的其他名称?

我应该在这里使用数组,还是有某种方法可以使用对象的名称,并且只是漂浮一堆对象,稍后可以在数组之外调用它们?

var TestApp = {};
    // my data... taken from wherever
    TestApp.jsonContacts = {
        contact1: {
            name: "Ethan",
            age: 24
        },
        contact2: {
            name: "Evan",
            age: 30
        },
        contact3: {
            name: "Paul",
            age: 9000
        }
    };
    // I know this is silly, just let me pretend it's strung from a server somewhere...
    TestApp.jsonStrung = JSON.stringify(TestApp.jsonContacts);
    TestApp.globalContactList = [];
    // my constructor function to create instances of Contact
    TestApp.Contact = function(name, age){
        this.name = name;
        this.age = age;
    };
    // where I'm taking data and creating new Contact objects
    TestApp.instantiateObjects = function(){
        // I know this is silly, just let me pretend I'm parsing it necessarily...
        var jsonUnstrung = JSON.parse(TestApp.jsonStrung);
        // I think I'm looping through the first set of objects sitting in jsonContacts
        for (var i in jsonUnstrung) {
            var obj = new TestApp.Contact(jsonUnstrung[i].name, jsonUnstrung[i].age);
            TestApp.globalContactList.push(obj);
        }
    };
    TestApp.instantiateObjects();

如果您只想将 JSON 转换为可用的模型,您可以循环并转换它,例如

TestApp.allContacts = {};
TestApp.instantiateObjects = function(){
    var jsonUnstrung = JSON.parse(TestApp.jsonStrung);
    for (var i in jsonUnstrung) {
        var obj = new TestApp.Contact(jsonUnstrung[i].name, jsonUnstrung[i].age);
        TestApp.allContacts[i] = obj;
    }
};

您将拥有具有相同密钥的所有实例。但是,当您将这些对象作为一个组使用时,您不应该通过它们的键来访问它们(除非您正在修改一个特定的对象),而应该迭代整个集合。如果它们以 JSON 或数组形式存储,则可以完成此操作,并且在其他地方有很多示例。如果您正在使用特定的密钥/索引,您应该有权访问密钥/索引,以执行当时所需的任何替换/删除。