使用 ReactJS 的脏话过滤器
Profanity Filter with ReactJS
考虑以下代码:
/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
import React from 'react'
import './App.css';
let swear = [
'arse',
'ass',
'asshole',
'bastard',
'bitch',
'bollocks',
'bugger',
'bullshit',
'crap',
'damn',
'frigger',
]
const App = () => {
let [count , setCount] = React.useState(0)
let [approval , setApproval] = React.useState(false)
let [text , setText] = React.useState('')
const bogusCheck = (text) =>{
swear.map(word => {
text.includes(word) === true ? (console.log('Bad word found') ): (console.log('No bad word found'));
})
}
return (
<div className="App">
<h1>Profanity Checker</h1>
<p>Enter a sentence below and click the button below:</p>
<textarea cols="30" rows='10' value={text} onChange={e => setText(e.target.value) } />
<br />
<button onClick={() => bogusCheck(text)} >Profanity Check</button>
</div>
);
}
export default App;
这应该是一个脏话过滤器。理论是它从文本区域获取输入,然后使用.map() 和.includes() 函数进行比较。
swear 是一个包含一些坏词的数组。
因此地图循环遍历 swear 数组,选取每个单词并查看它是否包含在文本中。如果 returns true 它控制台日志(发现坏词)。如果不是它记录(没有发现坏词)
问题是,当我单击该按钮时,它记录了 13 次不需要的结果,然后记录了一次需要的结果,然后记录了更多不需要的结果。见下图。
这个问题的解决方案是什么?
稍微更改一下代码:
const bogusCheck = (text) =>{
const foundSwears = swear.filter(word => text.toLowerCase().includes(word.toLowerCase()));
if(foundSwears.length){
console.log('Bad word found');
} else {
console.log('No bad word found');
}
})
考虑以下代码:
/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
import React from 'react'
import './App.css';
let swear = [
'arse',
'ass',
'asshole',
'bastard',
'bitch',
'bollocks',
'bugger',
'bullshit',
'crap',
'damn',
'frigger',
]
const App = () => {
let [count , setCount] = React.useState(0)
let [approval , setApproval] = React.useState(false)
let [text , setText] = React.useState('')
const bogusCheck = (text) =>{
swear.map(word => {
text.includes(word) === true ? (console.log('Bad word found') ): (console.log('No bad word found'));
})
}
return (
<div className="App">
<h1>Profanity Checker</h1>
<p>Enter a sentence below and click the button below:</p>
<textarea cols="30" rows='10' value={text} onChange={e => setText(e.target.value) } />
<br />
<button onClick={() => bogusCheck(text)} >Profanity Check</button>
</div>
);
}
export default App;
这应该是一个脏话过滤器。理论是它从文本区域获取输入,然后使用.map() 和.includes() 函数进行比较。
swear 是一个包含一些坏词的数组。
因此地图循环遍历 swear 数组,选取每个单词并查看它是否包含在文本中。如果 returns true 它控制台日志(发现坏词)。如果不是它记录(没有发现坏词)
问题是,当我单击该按钮时,它记录了 13 次不需要的结果,然后记录了一次需要的结果,然后记录了更多不需要的结果。见下图。
这个问题的解决方案是什么?
稍微更改一下代码:
const bogusCheck = (text) =>{
const foundSwears = swear.filter(word => text.toLowerCase().includes(word.toLowerCase()));
if(foundSwears.length){
console.log('Bad word found');
} else {
console.log('No bad word found');
}
})