Home » Javascript » JavaScript replace multiple if statements

JavaScript replace multiple if statements

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have couple of identical html pages and I would like to use the same JavaScript file which reads text files and changes data on the html pages. As the text files are different for every page I have done it with multiple if statements. It would be better if there is a way to replace it with some loop?

if (window.location.pathname=='/myapp/main.html') {
  $.get('data/data1.txt', function(data) {
     var bigarray = data.split('\n');
     bigarray.forEach(function(currRow){
       currentRow = currRow.split(';');
       table.push(currentRow);});
  }, 'text');
}

if (window.location.pathname=='/myapp/main2.html') {
  $.get('data/data2.txt', function(data) {
     var bigarray = data.split('\n');
     bigarray.forEach(function(currRow){
       currentRow = currRow.split(';');
       table.push(currentRow);});
  }, 'text');
}

if (window.location.pathname=='/myapp/main3.html') {
  $.get('data/data3.txt', function(data) {
     var bigarray = data.split('\n');
     bigarray.forEach(function(currRow){
       currentRow = currRow.split(';');
       table.push(currentRow);});
  }, 'text');
}

if (window.location.pathname=='/myapp/main4.html') {
  $.get('data/data4.txt', function(data) {
     var bigarray = data.split('\n');
     bigarray.forEach(function(currRow){
       currentRow = currRow.split(';');
       table.push(currentRow);});
  }, 'text');
}

Thank you in advance!

Answers: