Home > Software engineering >  Foreach loop to check for a value
Foreach loop to check for a value

Time:10-28

I have a foreach loop that loops through an array, then im running a callback function with the value of each item in the array as the parameter of the function, which is run once fore very item in the array. In the call back function i am trying to compare the value being passed with a string, but I always get a false nothing gets logged to console

This is my code

window.addEventListener('load', function() {
  let occupation = ["urologist", "urologist", "staff", "nurse", "surgeon"]

  occupation.forEach(function(occ) {
    let ab = occ.textContent
    let bc = ab.toLowerCase();
    chkfun(bc)
  })

  function chkfun(val) {
    if (val == "urologist") {
      console.log("urologist")
    }
    if (val == "surgeon") {
      console.log("surgeon")
    }
    if (val == "staff") {
      console.log("staff")
    }
    if (val == "nurse") {
      console.log("nurse")
    }
  }
}, false);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your problem is with the line let ab = occ.textContent. occ contains the text content already. You can just do bc = occ.toLowerCase()

Also take a look at JavaScript Switch instead of doing a bunch of if's

CodePudding user response:

You can call your function inside the forEach and it will be called with each element, there you can transform your value to lowercase and compare, also use a else if so the script will not test each value and stop as soon as it get a match. You can also add a else at the end for unknown elements

window.addEventListener('load', function() {
  let occupation = ["Urologist", "urologist", "staff", "nurse", "surgeon","a"];
  occupation.forEach(chkfun);
  function chkfun(v) {
    let val = v.toLowerCase();
    if (val == "urologist") {
      console.log("urologist")
    } else if (val == "surgeon") {
      console.log("surgeon")
    } else if (val == "staff") {
      console.log("staff")
    } else if (val == "nurse") {
      console.log("nurse")
    } else {
      console.log("element not found");
    }
  }
}, false);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related