简体   繁体   English

如何在 function 中包装一段代码?

[英]how do I wrap a piece of code inside a function?

I have this code written:我写了这段代码:

for(var i = 0; i < family.length; i++) {
      console.log(family[i].name) 
      console.log(`${family[i].name} has the following friends:${family[i].friends}`) 
    }

it actually go thorough each family member (all defined as objects) and displays the first name of the family member and then his friends...它实际上是 go 遍历每个家庭成员(都定义为对象)并显示家庭成员的名字,然后是他的朋友......

Now I want to wrap it in a function which prompts the user to enter a family member, if it exists it does as above, if not it alerts the user that the member is not listed and you need to add it as another object.现在我想把它包装在一个 function 中,它会提示用户输入一个家庭成员,如果它存在,它会像上面一样,如果不存在,它会提醒用户该成员未列出,您需要将其添加为另一个 object。 So I did this:所以我这样做了:

let input = window.prompt("Enter a name of a family member");

  function member() {
  
  if (input === family[family.name]) {

    for(var i = 0; i < family.length; i++) {
      console.log(family[i].name) 
      console.log(`${family[i].name} has the following friends:${family[i].friends}`) 
    }
}
  else {
    alert("This family member is not in my list - please add him");

  }
  
}

but is does not work...what am I doing wrong?但它不起作用......我做错了什么?

You need to add a way to execute member();您需要添加一种方法来执行 member();

I would execute member();我会执行 member(); after submitting the input.提交输入后。

You need to loop and actually call the function您需要循环并实际调用 function

 const family = [{ name: "fred", friends: [{ name: "frank" }] }, { name: "frank", friends: [{ name: "fred" }] } ] function member(input) { const found = family.filter(({name}) => name.includes(input)); if (found.length) found.forEach(person => console.log(person.name,`has the following friends: ${person.friends.map(friend => friend.name).join(', ')}`)) else { console.log("This family member is not in my list - please add him"); } } let input = window.prompt("Enter a name of a family member"); member(input)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM