-2

So after creating an object,I want to add it to an array but seem it doesn't working Only the last one was added and it looped.

I expect the output of mang[0] would be ('Samsung S8','s0','$200') but it doesn't.

It only show the last one ('Samsung A60','s2','$400'). It's the same to mang[1].

var mang=[];
 var Phone = {
            Name:'',
            Img:'',
            Price:'',
            them :function(name,img,price){
                this.Name=name;
                this.Img=img;
                this.Price=price;
                mang.push(Phone);
            }
        };
Phone.them('Samsung S8','s0','$200');
Phone.them('Samsung S10','s1','$300');
Phone.them('Samsung A60','s2','$400');
5
  • 3
    this, in them, is always the same. The intent of your design isn't clear, it seems random. Maybe you want classes ? Commented Jul 25, 2019 at 10:12
  • Could you please tell me more detail about it? Commented Jul 25, 2019 at 10:13
  • Maybe this? -> stackoverflow.com/questions/13190097/… Commented Jul 25, 2019 at 10:18
  • or stackoverflow.com/questions/2752868/… Commented Jul 25, 2019 at 10:19
  • Thank you I understand why my code doesn't work properly Commented Jul 25, 2019 at 10:23

2 Answers 2

1

Hi please try this solution

var PhoneList = [];
function Phone(Name,Img,Price){
    this.Name = Name; 
    this.Img = Img;
    this.Price = Price ; 
}


Phone.prototype.addToArray = function(){
    PhoneList.push(this); 
}

let phone1 = new Phone('Samsung S8','s0','$200');
phone1.addToArray();
let phone2 = new Phone('Samsung S10','s1','$300');
phone2.addToArray();
let phone3 = new Phone('Samsung A60','s2','$400');
phone3.addToArray();

console.log(PhoneList);

I hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks . Other way is you can use class. However I prefer function constructor over the class.
0

What you could consider is escapsulating that functionality in a class, where you can have a list of phones that you add to with one method (add), and another (logPhones) to log the list of phones that have been added.

class Phones {
  constructor() {
    this.phoneList = [];
  }
  add = (name, img, price) => {
    const phone = { name, img, price };
    this.phoneList.push(phone);
  }
  logPhones = () => {
    console.log(this.phoneList);
  }
}

const phones = new Phones();
phones.add('Samsung S8','s0','$200');
phones.add('Samsung S10','s1','$300');
phones.add('Samsung A60','s2','$400');
phones.logPhones();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.