I modified the following code from:
[url]https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_filter
It works OK, but I would like to change it further.
I wish to somehow pass the GLOBAL variable ‘state’
as part of the ‘filter’ function so as to avoid global assignments.
How is the information passed in the ‘filter’ function? ?
[code]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″ />
<title> filter() test </title>
<body>
<pre>
Count ‘y’ & ‘n’ & ‘-‘ characters
in this array [‘y’,’n’,’y’,’n’,’y’]
</pre>
<button onclick=”myFunction()”>Try it</button>
<pre id=”demo”></pre>
<script>
function doc(IDS) { return document.getElementById(IDS); } // reduce typing function
var consent = [‘y’,’n’,’y’,’n’,’y’],
state = ‘y’;
function checkConsent(YN) { return YN == state; }
function myFunction() {
state = ‘y’; doc(“demo”).innerHTML = ‘Y: ‘+ consent.filter(checkConsent).length+'<br>’;
state = ‘n’; doc(“demo”).innerHTML += ‘N: ‘+ consent.filter(checkConsent).length+'<br>’;
state = ‘-‘; doc(“demo”).innerHTML += ‘-: ‘+ consent.filter(checkConsent).length+'<br>’;
}
</script>
</body>
</html>