1

This one is probably fairly straightforward, but I haven't succeeded in finding an answer as of yet. Anyway, what I want to do is compare one value against a group of others, and run the script if it matches one of them. Here's the verbose version of I want to do, which works fine, but I'm assuming there's a smarter, less verbose way to achieve this?

function updatePosition(e) {
    if((e.target.innerHTML == 1) || (e.target.innerHTML == 4) || 
      (e.target.innerHTML == 7)) {
        console.log(e.target.innerHTML)
    }
}
SorenRomer
  • 217
  • 1
  • 10

1 Answers1

-1

You can store all the valid comparison inside an array. Then you can use Array#Find() to get a matching value. If there is no matching value, you will get undefined

function updatePosition(num) {
  let validNumbers = [1,4,7];
  console.log(validNumbers.find(valid => valid === num));
}

updatePosition(4);
updatePosition(9);
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • Why use `find` when you can use `includes` or `indexOf`? This also breaks on the value `0`, if you use it as a truthiness value like the question requires. – Ry- Sep 18 '17 at 13:38
  • @Ryan OP is comparing `e.target.innerHTML`. If he find it, he uses `e.target.innerHTML` inside `console.log()`. Using `find()` allows OP to directly use the value if he finds it. `includes` or `indexOf` will just tell him that he finds it. – Weedoze Sep 18 '17 at 13:51