微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-将forEach回调参数与函数参数结合

我正在尝试将forEach回调参数(HTMLAnchorElement / HTMLTableCellElement对象)与功能参数(字符串)结合在一起.

我正在做的是使用同一函数一个函数调用获取标签的href,然后在另一函数调用获取td标签的textContent.

这是我的代码

// example usage of function
await scraper.scraper(args,'a[href]','href') // get href

await scraper.scraper(args,'table tr td','textContent') // get textContent

// scraper function
const scraper = async (urls,regex,property) => {
  const promises = []
  const links = []

  urls.forEach(async url => {
    promises.push(fetchUrls(url))
  })

  const promise = await Promise.all(promises)
  promise.forEach(html => {
    const arr = Array.from(new JSDOM(html).window.document.querySelectorAll(regex))
    arr.forEach(tag => {
      links.push(tag.href) // how about textContent?
    })
  })

  return links
}

有没有办法将来自forEach的回调参数标签函数parameter属性结合在一起?

下面的代码有效.但是,如果我想对其他属性进行进一步的函数调用怎么办?我不想在每次调用一个函数时都添加一个if语句,这破坏了我函数的可重用性.
属性===’textContent’吗? links.push(tag.textContent):links.push(tag.href)

试图将两者结合的任何尝试似乎都是错误的.不可能吗

最佳答案
使用传入的属性值作为el对象的计算键(代码中的标记),以便根据传入的属性动态地传递forEach内部元素的属性

arr.forEach(el => {
  links.push(el[property]);
})

原文地址:https://www.jb51.cc/js/531117.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐