簡體   English   中英

我的JavaScript代碼有什么問題

[英]What is wrong with my JavaScript code

這是我正在做的練習: 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]);

您想對代碼的后兩部分執行printPerson,而不要重新創建該函數

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

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

一個大問題是,您使用相同的名稱定義了3次函數,並且從不調用它們。 您可以嘗試執行以下操作:

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

在第一個函數聲明之后,我還刪除了分號。

我相信您正在嘗試調用它們,而不是再次定義函數。

另外,您嘗試在函數中使用從未實際定義的變量。

你寫的地方

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

你應該寫

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

否則,您只是在重新定義函數,而不是調用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM