简体   繁体   中英

I have problem with adding my object to array

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM