【发布时间】: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