Javascript 结合forEach回调参数和函数参数
我试图将Javascript 结合forEach回调参数和函数参数,javascript,node.js,foreach,jsdom,Javascript,Node.js,Foreach,Jsdom,我试图将forEach回调参数(htmlanchorement/HTMLTableCellElement对象)与函数参数(string)组合起来 我所做的是在一个函数调用中获取href的a标记,然后在另一个函数调用中使用相同的函数获取td标记的textContent 这是我的密码: // example usage of function await scraper.scraper(args, 'a[href]', 'href') // get href await scraper.scrap
forEach
回调参数(htmlanchorement
/HTMLTableCellElement
对象)与函数参数(string
)组合起来
我所做的是在一个函数调用中获取href
的a
标记,然后在另一个函数调用中使用相同的函数获取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
的回调参数标记
与函数参数属性
组合起来
下面的代码可以工作。但是,如果我想对其他属性进行进一步的函数调用,该怎么办?我不想每次进行另一个函数调用时都添加if语句,这会破坏我的函数可重用的目的。property==='textContent'?links.push(tag.textContent):links.push(tag.href)
任何试图将两者结合起来的尝试似乎都是错误的。不可能吗?根据传入的属性,使用传入的属性值作为el对象的计算键(
tag
,在代码中),动态传递forEach
中元素的属性值
arr.forEach(el => {
links.push(el[property]);
})