0

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".

Junius L
  • 15,881
  • 6
  • 52
  • 96
Cory
  • 17
  • 6
  • 1
    You are overwriting the push method of Array.prototype. You have to call push like a function: product.push(new Products()); – Teemoh May 22 '17 at 19:42
  • if your query was solved please accept the answer that was useful. – Junius L May 22 '17 at 20:04

3 Answers3

2

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)
Junius L
  • 15,881
  • 6
  • 52
  • 96
1

push is a function, so you need to call it with parens push(). You are trying to use =, so it will not work.

In your case, you should do: product.push( new products(tag,"name", price, "path/to/my/item", "description") );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=control

Brian Glaz
  • 15,468
  • 4
  • 37
  • 55
1

First you should push like

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"));

and access the property like this product[0]["Name"] for reference check this out JavaScript property access: dot notation vs. brackets?

Opps my bad, it works with this product[0].Name also, property name is case sensitive, so change it to "Name"

Junius L
  • 15,881
  • 6
  • 52
  • 96
Neetigya
  • 121
  • 2
  • 10