Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same code, same browser, different behavior for users

I have a piece of JS code which parses through a file, then associated the array with a key-value pair map, and then iterates it through it to find the proper city name with a .includes method. My problem is that the final field (where the function in question is called) works fine on my end for both Chrome and Firefox. It does not work for some reason for my group members.

This is the JS snippet that does the iterating:

Edit: this is how the file is being opened:

var rawFile = new XMLHttpRequest();
    rawFile.open("GET", "../data/myFile.txt", false);

for (var i = 0; i < allText.length; i++) {
  if (i % 2 == 0) {
    myMap[allText[i]] = allText[i + 1];
  }
}

var city = document.getElementById("city").value;
for (var key in myMap) {
  if (myMap.hasOwnProperty(key)) {
    if (myMap[key].toLowerCase().includes(city.toLowerCase())) {
      document.getElementById("city").value = myMap[key]
      document.getElementById("zipcode").value = key;
    }
  }
}

This is the html part that calls it:

<label for="myLabel">City: </label>
<input type="text" name="myLabel" id="myLabel" onblur="readTextFile()">

What exactly is the problem and how can I troubleshoot it as it makes no sense to me, coming from the world of Java and C++, where I have never faced such an issue before. If you are wondering why the JS might be kinda ugly, it is the result of a student with a teacher who thinks that showing W3Schools examples is equivalent to good teaching.

like image 648
SomeStudent Avatar asked Sep 11 '16 01:09

SomeStudent


1 Answers

Javascript includes function may work erratically due to some browsers not supporting it. You need to be wise while choosing the javascript functions specially when mozilla may have some functions which are not supported on some browsers. W3schools also provides a list of Browser support for a function. Check the link below for that list for includes function:

http://www.w3schools.com/jsref/jsref_includes.asp

Alternatively, you can use indexOf function like:

     myMap[key].toLowerCase().indexOf(city.toLowerCase()) >= 0

I have myself faced issues with includes function hence providing you a workaround. Happy programming.

like image 130
Anshuman Avatar answered Nov 01 '22 12:11

Anshuman