Search code examples
javascriptfor-loopor-operator

Javascript: how to have a list of possible values a a variable can equal in an if construct


I want the value of my textarea to be a list of 1, 2, and 3s depending on the number provided in the prompt. However, it only works for the first number of each list.

list = "";
onclick = function() {
  room = prompt("room");
  if (+room == (108 || 110 || 112 || 401 || 403 || 405 || 600 || 601 || 602 || 603 || 604 || 605 || 606 || 607 || 608 || 611 || 613 || 615 || 617 || 619 || 621)) {
    list += "1";
    document.getElementById("p").value = list;
  }
  if (+room == (205 || 300 || 302 || 304 || 400 || 102 || 408 || 409 || 410 || 411 || 412 || 413 || 614 || 616 || 618 || 625 || 627 || 629)) {
    list += "2";
    document.getElementById("p").value = list;
  }
  if (+room == (301 || 305 || 307 || 310 || 311 || 312 || 313 || 314 || 315 || 316 || 317 || 320 || 321 || 323 || 324 || 325 || 326 || 327 || 331 || 404 || 501 || 512)) {
    list += "3";
    document.getElementById("p").value = list;
  }
};
<textarea id="p" /></textarea>


Solution

  • you can put the values in an array and then use .indexOf() here, like:

    if([108,110,112,401,403,405,600,601,602,603,604,605,606,607,608,611,613,615,617,619,621].indexOf(parseInt(room)) >= 0){
        list+="1";
        document.getElementById("p").value=list;
        }