简体   繁体   English

我的JavaScript代码有什么问题

[英]What is wrong with my JavaScript code

Here is the exercise I'm doing : http://www.codecademy.com/courses/building-an-address-book/0/3?curriculum_id=506324b3a7dffd00020bf661# 这是我正在做的练习: http : //www.codecademy.com/courses/building-an-address-book/0/3? curriculum_id= 506324b3a7dffd00020bf661#

Here is my code:

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

// printPerson added here
function printPerson(person){
    console.log(firstName);
    console.log(lastName);
};

function printPerson(){
        console.log(contacts[0]);
}
function printPerson(){
        console.log(contacts[1]);
}
var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: "bob.jones@example.com"
};

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

// printPerson added here
function printPerson(person){
    console.log(person.firstName + " "+ person.lastName);   
}

printPerson(contacts[0]);
printPerson(contacts[1]);

You are wanting to execute printPerson for the last two parts of the code and not recreate the function 您想对代码的后两部分执行printPerson,而不要重新创建该函数

function printPerson(person){
    console.log(person.firstName);
    console.log(person.lastName);
};

printPerson(contacts[0]);
printPerson(contacts[1]);

One big problem is that you define functions with the same name 3 times and never call them. 一个大问题是,您使用相同的名称定义了3次函数,并且从不调用它们。 You could try doing something like this instead: 您可以尝试执行以下操作:

// printPerson added here
function printPerson(person){
    console.log(firstName);
    console.log(lastName);
}
printPerson(contacts[0]);
printPerson(contacts[1]);

I also removed the semicolon after the first function declaration. 在第一个函数声明之后,我还删除了分号。

I believe you are trying to call them instead of define the function again. 我相信您正在尝试调用它们,而不是再次定义函数。

Also, you are trying to use variables in your function that are never actually defined. 另外,您尝试在函数中使用从未实际定义的变量。

where you've written 你写的地方

function printPerson(){
        console.log(contacts[0]);
    }
function printPerson(){
        console.log(contacts[1]);
    }

You should have written 你应该写

printPerson(contacts[0]);
printPerson(contacts[1]);

Otherwise you're just redefining the functions instead of calling them. 否则,您只是在重新定义函数,而不是调用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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