How to add object to arrays?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • aliensite

    How to add object to arrays?

    <html>
    <body>
    <script>
    // object constructor
    function names(fname,lna me){
    this.fname=fnam e;
    this.lname=lnam e
    }
    // object arrays
    list = new Array()
    list[0]=new names("Dave","S mith")
    list[1]=new names("Mary","B rown")

    //add object ("Sue","Wood ") to arrays
    // How?

    // list fname
    for(var i=0;i<list.leng th;i++){
    alert(list[i].fname)
    }
    </script>
    </body>
    </html>
  • Douglas Crockford

    #2
    Re: How to add object to arrays?

    > // object constructor[color=blue]
    > function names(fname,lna me){
    > this.fname=fnam e;
    > this.lname=lnam e
    > }
    > // object arrays
    > list = new Array()
    > list[0]=new names("Dave","S mith")
    > list[1]=new names("Mary","B rown")[/color]


    If the objects lack methods, it is better to simply use the literal object
    notation.

    var list = [
    {fname: "Dave", lname: "Smith"},
    {fname: "Mary", lname: "Brown"}];
    [color=blue]
    > //add object ("Sue","Wood ") to arrays
    > // How?[/color]

    list.push({fnam e: "Sue", lname: "Brown"});



    Comment

    Working...