Kevin Kevin - 1 year ago 26
Javascript Question

Undefined while pushing OBJ in Array

i'm trying to create items in canvas for a website that i'm creating.
While using an Object and Array push I used an Alert to indicate me what's in the Array but it tells me that it's undefined.
Any suggestion on how I can fix that or did I do something wrong in my JS.
Thank you

function products(tag, name, price, src, description){
this.Tag = tag;
this.Name = name;
this.Price = price;
this.Src = src;
this.Description = description;
}

var product = [];

product.push = new products(tag,"name", price, "path/to/my/item", "description");


When I do this with all my real informations and I do a "alert(product[0].name)" it doesn't show me the name it gives me an "Cannot read property 'name' of undefined" error and when I do a "alert(product[0])" theres an alert but it tells me "Undefined".

Answer Source

change your code to the following, you are assigning your product to .push()

The push() method adds new items to the end of an array, and returns the new length.

product.push(new products(tag,"name", price, "path/to/my/item", "description"));

When you use

product.push = new products(tag,"name", price, "path/to/my/item", "description");

push becomes the property of product

enter image description here

 function products(tag, name, price, src, description){
        this.Tag = tag;
        this.Name = name;
        this.Price = price;
        this.Src = src;
        this.Description = description;
    }

    var product = [];

    product.push(new products('just a tag',"Kevin", 'price', "path/to/my/item", "description"));
    alert(product[0].Name)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download