JS学习过程中碰到的小问题

时间:2022-02-08 15:37:38

使用循环语句查找通讯录

 1 //Setup
 2 var contacts = [
 3 {
 4 "firstName": "Akira",
 5 "lastName": "Laine",
 6 "number": "0543236543",
 7 "likes": ["Pizza", "Coding", "Brownie Points"]
 8 },
 9 {
10 "firstName": "Harry",
11 "lastName": "Potter",
12 "number": "0994372684",
13 "likes": ["Hogwarts", "Magic", "Hagrid"]
14 },
15 {
16 "firstName": "Sherlock",
17 "lastName": "Holmes",
18 "number": "0487345643",
19 "likes": ["Intriguing Cases", "Violin"]
20 },
21 {
22 "firstName": "Kristian",
23 "lastName": "Vos",
24 "number": "unknown",
25 "likes": ["Javascript", "Gaming", "Foxes"]
26 }
27 ];
28 
29 
30 function lookUpProfile(firstName, prop){
31 
32 var hasName = false;
33 //设置标量hasName,作为firstName判定的结果
34 for (var i = 0; i < contacts.length; i++) {
35     if (contacts[i].firstName == firstName) {
36         hasName = true;
37         if (contacts[i].hasOwnProperty(prop)) {
38             return contacts[i][prop];
39         } else {
40             return "No such property";
41         }
42     }
43 }
44 
45 if(!hasName){
46     //等循环执行完之后再对是否有firstName的判定结果进行处理,避免影响prop属性的判定过程
47     return "No such contact";
48 }
49 
50 }
51 
52 
53 lookUpProfile("Akira", "likes");