0

New programmer here. After back-breaking hours of research, I was able to come up with a solution for a problem that would hide a message if the user was external, or would show the message if the user was internal.

I would grab the user's IP using an API from apify.org, store it into a variable of IP, and manually compare that specific IP to a string.

if (ip=='123.123.124.108' || ip=='124.10.50.255' ) 
             document.getElementById('message').style.display = 'block';
    else
             document.getElementById('message').style.display = 'none';
  }

But, if I stored the above-mentioned IP's in an array and used a for-loop to go through the array, to check if the user was internal or external if index[0] matched. If I placed it anywhere else within the array, the message would be hidden even if the user was internal.

var baseIP = ['123.123.124.108','124.10.50.255','218.105.111.11','45.81.255.255'];
    
for (let i = 0; i<baseIP.length; i++);
    if (ip == baseIP[i]) {
      document.getElementById('message').style.display = "block"
    } else
      document.getElementById('message').style.display = "none"
  }

Any insight would be greatly appreciated.

  • Your loop method applies the check for every element, so only the last element matters. Use `.includes` instead – CertainPerformance Jun 27 '21 at 21:56
  • So would it be more along the lines if (ip.includes(baseIP[i]))...? – here2learn Jun 28 '21 at 17:04
  • Other way around. `baseIP.includes(ip)` Also consider using more informative variable names, like `ipArr` or `internalIps` or something of the sort – CertainPerformance Jun 28 '21 at 17:22
  • that seemed to do the trick! One other question, let's say that I wanted to have a range of IP's, so i wanted to use the first three octets. .includes() seems to work for the full ip, but not the range? so 123.123.124.100 works but not 123.123.124 ? – here2learn Jun 28 '21 at 18:12

0 Answers0