JavaScript 使用循环语句查找通讯录
1
我们有一个联系人列表,里面存储着不同联系人的数组对象。
函数 lookUpProfile
有两个预定义参数:firstName
值和prop
属性 。
该函数应检查firstName是实际联系人的firstName,给定的属性(prop)是该联系人的属性。
如果它们都存在,函数返回prop
属性对应的值。
如果firstName
值不存在,返回 "No such contact"
。
如果prop
属性不存在,返回 "No such property"
。
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
for( var i = 0; i < contacts.length; i++){
if(firstName == contacts[i]["firstName"]){
if(contacts[i][prop]){
return contacts[i][prop];
}
else{
return "No such property";
}
}
return "No such contact"; //循环执行结束后返回这一句
}
应该为 if(i == contacts.length-1 ){
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
for( var i = 0; i < contacts.length; i++){
if(firstName == contacts[i]["firstName"]){
if(contacts[i][prop]){
return contacts[i][prop];
}
else{
return "No such property";
}
}
return "No such contact"; //循环执行结束后返回这一句
}
应该为 if(i == contacts.length-1 ){
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
2
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line
将一个 零到一之间的随机数 * (myMax - myMin + 1) 后向下取整+myMin
作用是保证myMax和myMin之间的每个数都能取到,记录重点在+1,保证能取到myMax
}