所以基本上我写了这个JS函数来过滤来自网络论坛的一些帖子内容。
const postFilter = (vector) => {
vector.forEach(e => {
e.innerHTML.toLowerCase().match(/word1|word2|word3/g) ? e.style.display = 'none' : false;
});
}
postFilter(document.getElementById('threadbits_forum_2').querySelectorAll('tr'));以下是我的问题:
foreach方法是函数友好的吗?那么正则表达式呢?如果我将正则表达式声明为常量,它仍然是一个纯函数吗?
发布于 2019-05-02 18:25:27
如果我将正则表达式声明为常量,它仍然是一个纯函数吗?
使用常量的函数仍然是纯函数。这只是“另一个函数参数”。将常量等同于隐藏函数组合。
伪码:
func a(c) {
return func b(p) {
return c + p
}
}
const c1 = 5
a(c1)(6) = 11
a(c1)(7) = 12
...您的函数的问题是对DOM的副作用。当您在DOM中进行更改时,其他流程也可以更改相同的元素。这不是一个函数式方法。阅读更多关于如何使用更多函数式方法处理DOM的副作用。
此外,对于您的情况,请使用map而不是foreach。
发布于 2019-05-02 20:02:30
你混淆了几个不同的东西:
根据其contents
的正则表达式匹配,
第三个是有问题的,因为它本质上是非功能性的(从技术上讲,第一个也可以,但我们将假装HTML不能改变)。在函数式范例中,您希望将逻辑与执行副作用的代码分开:
// Pull out the filtering logic into a pure (for Javascript) function
const filterElement = regex => elem => elem.innerHTML.match(regex);
// Pull the side-effect out into an impure function
const hide = elem => elem.style.display = 'none';
[ ...document.getElementById('threadbits_forum_2').querySelectorAll('tr') ]
.filter(filterElement(/word1|word2|word3/gi)) // note the i flag
.forEach(hide);https://stackoverflow.com/questions/55949667
复制相似问题