So this code is meant to take an array (which is represented by different people in someone's contact list) and use a lookUp function with two arguments (a person's first name and a property, both provided by the user, to determine:
- whether or not the person is in fact in your contact list
- whether or not the property actually exists in that person's individual array
If both values return true, print the value of the property provided
function lookUp(firstName, prop){ var i; var newArray = []; for (i = 0; i < contacts.length; i++) { var fn = contacts[i].firstName; newArray.push(fn); } var foundName = $.inArray(arguments[0], newArray) > -1; if (foundName === true){ var place = $.inArray(arguments[0], newArray); var property = arguments[1]; if (property == "likes"){ return contacts[place].likes; } else if (property == "number"){ return contacts[place].number; } else if (property == "lastName"){ return contacts[place].lastName; } else { return "No such property"; } } else { return "No such contact"; }
And an example array for sake of ease:
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
Now the function works fine as is, but in my previous version I had this to output the property of an existing contact:
var foundName = $.inArray(arguments[0], newArray) > -1;
if (foundName === true){
var place = $.inArray(arguments[0], newArray);
var property = arguments[1];
return contacts[place].property;
} else {
return "No such contact";
}
Instead of the revised "workaround" of my new code, this:
var foundName = $.inArray(arguments[0], newArray) > -1;
if (foundName === true){
var place = $.inArray(arguments[0], newArray);
var property = arguments[1];
if (property == "likes"){
return contacts[place].likes;
} else if (property == "number"){
return contacts[place].number;
} else if (property == "lastName"){
return contacts[place].lastName;
} else {
return "No such property";
}
} else {
return "No such contact";
}
With the previous version of code, even though var property is equal to "likes," nothing would be returned; contacts[place].likes would return a list of likes, but contacts[place].property would return nothing at all. Hence my workaround code, in which I just take each property one-by-one to see if it exists. Why exactly does this happen? Why can't a variable (which means literally exactly the same thing) take the place of the property in question, and achieve the same results?