我正在创建这个函数(它在JavaScript中的问题)。运行代码给了我一个
语法错误:意外令牌=
我似乎无法弄清楚错误是什么。我认为这是由于这段代码引起的:
contacts[contacts.length]
但我不确定,因为有人告诉我这可能吗?哦,contacts
是一个数组。我想要做的是将对象添加到数组的末尾。任何帮助将不胜感激,我对JS很新。这是我的全部功能:
function add(firstName, lastName, email, phoneNumber) {
contacts[contacts.length] = {
firstName = this.firstName,
lastName = this.lastName,
email = this.email,
phoneNumber = this.phoneNumber
};
};
add("Ross", "Lynch", "rossShorR5@r5rocks.com", "(650) 222-2222");
list();
答案 0 :(得分:1)
键/值对列表以逗号分隔,每个键和值用冒号和:
分隔,以便将键与值分开。继续阅读JavaScript Objects
您的正确代码是:
function add(firstName, lastName, email, phoneNumber) {
contacts[contacts.length] = {
firstName : this.firstName,
lastName : this.lastName,
email : this.email,
phoneNumber : this.phoneNumber
};
};
add("Ross", "Lynch", "rossShorR5@r5rocks.com", "(650) 222-2222");
list();
答案 1 :(得分:0)
使用“this”执行此操作的另一种方法是:
functon Contact(firstName, lastName, email, phoneNumber)
{
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phoneNumber = phoneNumber;
}
function addContact(firstName, lastName, email, phoneNumber)
{
contacts[contacts.length] = new Contact(firstName, lastName, email, phoneNumber);
}
addContact("Ross", "Lynch", "rossShorR5@r5rocks.com", "(650) 222-2222");