[英]Could you explain me this block of code? (Contact List)
我自己學習JavaScript,首先閱讀了教程和書籍(例如Eloquent)和文章(例如在Medium上)。 我也在做一些免費課程,特別是兩個:freeCodeCamp和CodeAcademy。
今天,我不得不面對CodeAcademy上的聯系人列表練習,但不確定自己是否正確理解。
經過一些提示,這是我想出的最終代碼:
var friends = { bill: { firstName: "Bill", lastName: "Gates", number: "555 555 555", address: ["One Miscrosoft Way", "Redmond", "WA", "98052"] }, steve: { firstName: "Steve", lastName: "Jobs", number: "333 333 333", address: ["Apple's street", "Silicon Valley", "SV", "87368"] } }; var list = function(friends) { for (var firstName in friends) { console.log(firstName); } }; var search = function(name) { for (var key in friends) { if (friends[key].firstName === name) { console.log(friends[key]); return friends[key]; } } }; list(friends); search("Steve");
.as-console-wrapper { max-height: 100% !important; top: 0; }
我了解了var friends對象和第一個功能。 但是第二個函數呢? 如果不在聯系人列表中,為什么我需要使用“名稱”和“關鍵字”這兩個詞。 您能解釋一下代碼的實際作用嗎?
此外,在練習結束時,CodeAcademy將最后的代碼用於執行我想像的操作:
list(friends);
search("Steve");
到底是什么
另請: for ...在循環中
// basically the same thing as doing
// function search(name){...}
// this just creates a function in this scope
var search = function(name) {
// for..in loop loops through the property
// names in the friends object
for (var key in friends) {
// "key" has the value of either "steve" or "bill"
// if key === steve then friends[key] is the same
// thing as doing friends.steve
// if friends.steve.firstName === name
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
好的,所以您有var friends,這是一個對象,其中包含每個也是對象的“ friend”。 var friends中的每個單獨的friend對象包含屬性(名字,姓氏等)。
var search = function(name) {
for (var key in friends) {
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
看來這是您迷路的地方。 好的,因此您創建搜索並將其設置為功能。 在函數內部,您傳遞名稱,這里引用了friends[key].firstname === name
。 [key]實際上是引用“ friends”中那些“ friend”屬性中的每一個,因此Bill是一個密鑰。 因此,它將查看這些鍵中的每個鍵(帳單,史蒂夫等),並將該鍵的名字設置為name,這是先前傳遞的。 因此,當您使用該功能時search("Steve");
它實際上是要在該對象列表中找到他,並返回“ steve”具有的所有屬性,例如名字地址等。
基本上可以總結一下。 函數中傳遞的“名稱”僅允許您搜索“朋友”,而[key]將允許for循環搜索朋友的所有鍵。
在這個功能中:
var search = function(name) {
for (var key in friends) {
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
變量key
是指每次迭代中對象friends
每個鍵,這意味着它的值在第一次迭代中為“ bill”,而在第二次迭代中為“ steve”。
name
是此函數search
的參數,在執行search('Steve')
類的函數之前,它沒有實際值,請參見為其分配值'Steve'
。
因此, list(friends)
在控制台中打印'bill'和'steve',而search('Steve')
將打印此對象:
{
firstName: "Steve",
lastName: "Jobs",
number: "333 333 333",
address: ["Apple's street", "Silicon Valley", "SV", "87368"]
}
然后退回
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.