[英]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.我希望
mang[0]
的输出是('Samsung S8','s0','$200')
但它不是。
It only show the last one ('Samsung A60','s2','$400')
.它只显示最后一个
('Samsung A60','s2','$400')
。 It's the same to mang[1]
. 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
封装该功能,您可以在其中使用一种方法 ( add
) 添加电话列表,并使用另一种方法 ( logPhones
) 记录已添加的电话列表。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.