【问题标题】:output elements of an array containing particular letter in javascriptjavascript中包含特定字母的数组的输出元素
【发布时间】:2020-03-04 13:58:55
【问题描述】:

我是 javascript 新手,我正在努力在我的函数上使用正确的语法来从包含字母“i”的数组中提取元素。


let teachers = ["Arrington", "Kincart", "Alberts", "Pickett"]

let rooms = [
  ["Andy", "Rodolfo", "Lynn", "Talia"],
  ["Al", "Ross", "Jorge", "Dante"],
  ["Nick", "Kim", "Jasmine", "Dorothy"],
  ["Adam", "Grayson", "Aliyah", "Alexa"]
]

let iInName = (teacher) => {
  let nameWithI = []
  teachers.forEach((withI) => {
    if(teacher.includes('i') {
    nameWithI.push(withI)
  }
})
return nameWithI
}

iInName()


非常感谢任何见解。这是我第一次在这里发帖;如果我遗漏了任何信息或忽略了任何礼仪,我很乐意解决!

【问题讨论】:

  • 请向我们展示完整的代码。您发布的内容似乎错过了teachers 的声明和函数的第一行。
  • 您遇到的语法错误是什么?

标签: javascript arrays function syntax include


【解决方案1】:

How to use the forEach method

withI 被传递给您定义的这个函数 (callback)。 teachers 是名称数组,每个名称都会调用withI

if(teacher.includes('i') 应该是 if(withI.includes('i')),因为 withI 是老师的名字。

您可能还想查看Array.prototype.filter

function iInName(teachers) {
  let nameWithI = []
  teachers.forEach((withI) => { // A function or commonly referred to as a callback
    if(withI.includes('i') { // Changed from teachers (of type array)
      nameWithI.push(withI)  // To withI (type string)
    }
  })
  /*
   return teachers.filter((name) => {
      return name.includes('i') // Keeps value if true
    })
  */
  // return teachers.filter(name => name.includes('i'))
  return nameWithI
}
iInName(['joe', 'marie']) // Any array

您只需要三个解决方案之一,一个用/**/ 注释掉,另一个用// 注释掉。最相似的是未注释(使用)。

【讨论】:

  • 非常感谢您的洞察力。
  • 没问题^-^。您需要任何进一步的帮助吗?如果没有,您可以选择此答案作为回答您问题的答案。
猜你喜欢
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 2021-12-20
  • 1970-01-01
相关资源
最近更新 更多