有人可以帮我创建一个包含所有属性的新对象并插入phonebook
数组吗?
var phonebook = [
{
firstName: "John",
lastName: "Doe",
phoneNumber: "000/111-111",
address: ['street', '1', 'city', '00000']
},
{
firstName: "John1",
lastName: "Doe1",
phoneNumber: "000/111-111",
address: ['street', '2', 'city', '00000']
},
//add new one here;
];
phonebook.addNewContact = function(fname, lname, phonenum, address){
this.firstName = fname;
this.lastName = lname;
this.phoneNumber = phonenum;
this.address= address;
}
答案 0 :(得分:0)
你可以这样做,基本上只是调用你创建的方法,但我建议你使用一个构造函数:
var phonebook = [
{
firstName: "John",
lastName: "Doe",
phoneNumber: "000/111-111",
address: ['street', '1', 'city', '00000']
},
{
firstName: "John1",
lastName: "Doe1",
phoneNumber: "000/111-111",
address: ['street', '2', 'city', '00000']
},
//add new one here;
];
phonebook.addNewContact = function(fname, lname, phonenum, address){
this.firstName = fname;
this.lastName = lname;
this.phoneNumber = phonenum;
this.address= address;
}
var newperson = new phonebook.addNewContact('john', 'doe', '000/111-111', ['street', '3', 'city', '00000']);
答案 1 :(得分:0)
您可以使用push功能实现此目的:
例如:
var phonebook = [
{
firstName: "John",
lastName: "Doe",
phoneNumber: "000/111-111",
address: ['street', '1', 'city', '00000']
},
{
firstName: "John1",
lastName: "Doe1",
phoneNumber: "000/111-111",
address: ['street', '2', 'city', '00000']
}
];
function addNew(fname, lname, phonenum, address){
phonebook.push({
firstName: fname,
lastName: lname,
phoneNumber: phonenum,
address: address
});
}
答案 2 :(得分:0)
看起来您正在尝试添加到电话簿阵列,如果这是您想要的,那么您可以这样做:
var phonebook = [
{
firstName: "John",
lastName: "Doe",
phoneNumber: "000/111-111",
address: ['street', '1', 'city', '00000']
},
{
firstName: "John1",
lastName: "Doe1",
phoneNumber: "000/111-111",
address: ['street', '2', 'city', '00000']
}
];
var addNewContact = function(fname, lname, phonenum, address){
phonebook.push({
firstName: fname,
lastName: lname,
phoneNumber: phonenum,
address: address
});
};
addNewContact('Jamie', 'Bonnett', '000/111-111', ['street', '0', 'city', '00000']);
document.write('<pre>' + JSON.stringify(phonebook) + '</pre>');
&#13;