【问题标题】:Combine forEach callback parameter with function parameter结合 forEach 回调参数和函数参数
【发布时间】:2019-01-24 23:33:36
【问题描述】:

我正在尝试将forEach 回调参数(HTMLAnchorElement/HTMLTableCellElement 对象)与函数参数(string)结合起来。

我正在做的是在一个函数调用中获取a 标记的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中的回调参数tag与函数参数property结合起来?

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

任何试图将两者结合起来的尝试似乎都会出错。不可能吗?

【问题讨论】:

    标签: javascript node.js foreach jsdom


    【解决方案1】:

    使用您传入的属性值作为 el 对象的计算键(代码中的 tag),以便动态传递 forEach 内元素的属性值,具体取决于您传入的属性

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

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 2012-07-07
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      相关资源
      最近更新 更多