2013-12-20 157 views
-3

所以我試着運行下面的代碼,但它不會循環訪問'contacts'數組,並運行printPerson函數。如何讓它在bob和Mary上打印這兩個信息。意外的循環行爲

var bob = { 
    firstName: "Bob", 
    lastName: "Jones", 
    phoneNumber: "(650) 777-7777", 
    email: "[email protected]" 
}; 

var mary = { 
    firstName: "Mary", 
    lastName: "Johnson", 
    phoneNumber: "(650) 888-8888", 
    email: "[email protected]" 
}; 

var contacts = [bob, mary]; 

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

var list = function() { 
    var contactsLength = contacts.length; 
    for (i=0; i > contacts.length; i++) { 
     printPerson(contacts[i]); 
    } 
}; 
list(); 
+1

它應該是'我 dirkk

+1

出於好奇,你爲什麼要定義'contactsLength'而不使用它? – putvande

+0

對不起,我忘記擦除,我是新來的JavaScript。 –

回答

3

您有循環的一個錯字:

for (i=0; i > contacts.length; i++) 
      ^------------Change to < 
1

變化:i > contacts.length通過i < contacts.length在for循環

1

看看能否cicle 它應是i < contacts.length而不是i > contacts.length