【问题标题】:How to add object to array in constructor如何在构造函数中将对象添加到数组
【发布时间】:2014-09-18 13:39:22
【问题描述】:

我正在使用 JavaScript 进行编程,我创建了一个名为 users 的数组和一个用于 user 对象的构造函数。每次创建新对象时,我都想将其添加到数组中。

var users = [];


function user(username, password){
    this.username = username;
    this.password = password;
    users[users.length-1] = this;
};

var joe = new user('Joe', "joe100");

上面的方法似乎不起作用。如何在构造函数中将对象添加到数组中?

【问题讨论】:

  • 去掉-1

标签: javascript html arrays oop constructor


【解决方案1】:

"users" 是一个空数组,这意味着当您点击构造函数时,它的长度为 0。因此,将“this”分配给 length-1 意味着将“this”分配给“-1”索引......这就是它不起作用的原因......摆脱 -1,或者...

也许使用 javascript array.push() 函数来添加到您的数组中

查看 W3Schools 网站上的示例... Array#push

【讨论】:

    【解决方案2】:

    只需从您的代码中删除 -1,它就会如下所示

    var users = [];
    
    
    function user(username, password){
        this.username = username;
        this.password = password;
        users[users.length] = this;
    };
    
    var joe = new user('Joe', "joe100");
    

    为您准备的 HTML Demo 代码示例

    <!DOCTYPE html>
    <html>
    <body>
    
    <p id="demo"></p>
    
    <script>
    var users = [];
    
    
    function user(username, password){
        this.username = username;
        this.password = password;
        users[users.length] = this;
    };
    
    var joe = new user('Joe', "joe100"),l = new user('ll', "ll99");
    
    document.getElementById("demo").innerHTML = users[0].username+"   ---  "+users[0].password+"<br/>"+users[1].username+"   ---  "+users[1].password;
    </script>
    
    </body>
    </html>
    

    我想这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-04-22
      • 1970-01-01
      • 2021-04-26
      • 2013-10-27
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2021-06-15
      • 2018-03-19
      相关资源
      最近更新 更多