因此,在创建对象之后,我想将其添加到数组中,但似乎不起作用 仅添加了最后一个,并且循环了。
我希望mang[0]
的输出为('Samsung S8','s0','$200')
,但不是。
它仅显示最后一个('Samsung A60','s2','$400')
。与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');
答案 0 :(得分:1)
您好,请尝试此解决方案
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);
我希望它会有所帮助。
答案 1 :(得分:0)
您可能会考虑将功能封装在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();