Forbes magazine logo Ranked Best Coding Bootcamps 2023

Profile Lookup

Altcademy Team wrote on 7 February 2018

function lookUp(firstName, prop) { for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === firstName && contacts[i][prop]) { return contacts[i][prop]; } else if (contacts[i][prop] === undefined) { return "No such property"; } else if (contacts[i].firstName === undefined) { return "No such contact"; } } }

I believe you are looking for this solution?
for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === firstName) { if (contacts[i].hasOwnProperty(prop)) { return contacts[i][prop]; } else { return "No such property"; } } } return "No such contact";

为什么要在外层返回No such contact?

Answer
如果在内层返回,会过早返回,就是说还没有测试完全部的 contacts 前,就已决定没有 contact 的名字和 firstname 相符。

我们的目的是想知道 contacts 里有没有一个跟我们要找的名字一样,如果有,就看看他有没有我们找的 prop。如果有 prop ,就返回这个 prop 的函数,如果没有就返回 "No such property"。我们需要查看所有的 contacts 才能决定里面没有我们要找的 firstname。


Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #89

Enroll for May 6th, 2024