[英]How do I get the list of mutual friends on Facebook using their API?
[英]8.12.5: Mutual Friends CodeHS
這是給定的問題:
編寫一個程序,打印兩個人之間的共同朋友。
您應該創建兩個集合,每個人一個,並將代表該人的朋友的朋友(字符串)添加到每個集合。
然后,填寫以兩人為參數的mutualFriends function,並返回一個包含他們共同朋友的新集合。
打印出一組共同的朋友
提示 有多種方法可以做到這一點。 並非所有提示都適用於每種方法。
您可以像這樣遍歷集合中的元素:
for (item of your_set) {
println(item);
}
您可以像這樣使用 set 方法 union 或 intersect :
// returns a set which is the union of a and b
var aUnionB = a.union(b);
// returns a set which is the intersection of a and b
var aIntersectB = a.intersect(b);
這是我做的代碼:
function start(){
// Create your friend lists here
var friendOne = new Set ("Timmy", "John", "Greg", "Sophia", "Kate");
var friendTwo = new Set ("Nate", "John", "Kate", "Timmy", "Lee");
mutualFriends(friendOne, friendTwo);
}
/* This function takes two people, a, b
* which are sets of their friends.
* It returns a new set that holds the
* mutual friends of a and b.
*/
function mutualFriends(a, b) {
// Write this function here
var friends = [];
for (var items in a && b) {
if(a.contains(items in b)){
friends.add(items);
}else if(b.contains(items in a)){
friends.add(items);
}else{
println("Not working.");
}
}
println("A and B's mutual friends are: " + friends);
return friends;
}
相反,我的代碼不顯示共同的朋友並忽略 if 語句。 任何幫助將不勝感激,謝謝!
您的原始代碼中存在一些語法問題。
(1) 如果你想從兩個列表中得到共同的朋友,你只需要比較一次(比如比較listA和listB),不需要再次比較listB和listA。
(2)請用“has”檢查listB是否在listA中有好友
請在下面找到演示所需內容的代碼:
<script>
let friendOne = new Set (["Timmy", "John", "Greg", "Sophia", "Kate"]);
let friendTwo = new Set (["Nate", "John", "Kate", "Timmy", "Lee"]);
let mutualfriend=new Set ();
for (let item of friendOne){
if (friendTwo.has(item)){
mutualfriend.add(item);
}
}
document.write("The mutual friends are:<br>");
for (let mfriend of mutualfriend){
document.write(mfriend);
document.write("<br>");
}
</script>
您可以使用 union / intersect 進一步修改您的代碼。 如有必要,請嘗試處理它。
我想出了怎么做。 這僅適用於 codeHS。
function start(){
// Create your friend lists here
var friendOne = new Set ();
var friendTwo = new Set();
//Friends of friendOne
friendOne.add("Timmy");
friendOne.add("John");
friendOne.add("Greg");
friendOne.add("Sophia");
friendOne.add("Kate");
println(friendOne);
//Friends of friendTwo
friendTwo.add("Nate");
friendTwo.add("Kate");
friendTwo.add("John");
friendTwo.add("Timmy");
friendTwo.add("Lee");
println(friendTwo);
mutualFriends(friendOne, friendTwo);
}
/* This function takes two people, a, b
* which are sets of their friends.
* It returns a new set that holds the
* mutual friends of a and b.
*/
function mutualFriends(a,b){
var friends = new Set();
for(var item of a){
if (b.contains(item)){
friends.add(item);
}
}
for(var item of b){
if (a.contains(item)){
friends.add(item);
}
}
println("Mutual friends are: " + friends);
return friends;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.