Search code examples
javascriptarraysvar

How do I populate a list of vars?


I am trying to organize my code so that it doesn't look so dumb.

var date = new Date();
  
var tokyo = new Date().toLocaleDateString("ja-JP");
var londo = new Date().toLocaleDateString("en-US");

document.getElementById('Tokyo').innerHTML = tokyo;
document.getElementById('London').innerHTML = london;

This may look ok for 2-3 cities but as more & more cities get added, this code will begin to look really redundant/silly.

So I tried to populate the html element li and put each city inside of each li.

var cityList = ['london', 'tokyo'];

function populateCities() {
  var list = document.querySelector(".cities");

  var li;
  for (var e = 0; e & lt; cityList.length; e++) {
    li = document.createElement("li");
    li.appendChild(document.createTextNode(cityList[e]));
    list.appendChild(li);
  }

  var date = new Date();

  var tokyo = new Date().toLocaleDateString("ja-JP");
  var londo = new Date().toLocaleDateString("en-US");
}

window.onload = populateCities;

And instead of displaying each city's date, each li literally puts the city name (text) in it.

I think I need to put the argument instead of the literal in the var but I just don't know enough javascript to fix the above code.

Just trying to learn javascript. Any help will be greatly appreciated it.


Solution

  • cityList should be a data structure that holds both the city name and the city code (used by toLocaleDateString), for which an object {} is more suitable than an array, like so:

    var cityList = {
      london: "en-GB",
      tokyo: "ja-JP",
      /* more cities and their codes */
    };
    

    Using a for..in loop like for(var city in cityList), we can access the city name via city and the city code via cityList[city], and use them to populate the list like so:

    var cityList = {
      berlin: "de-DE",
      cairo: "ar-EG",
      london: "en-GB",
      "new york": "en-US",
      paris: "fr-FR",
      seoul: "ko-KR",
      tokyo: "ja-JP"
    };
    
    function populateCities() {
      var list = document.querySelector("#cities");
      var date = new Date();
    
      for (var city in cityList) {
        var li = document.createElement("li");
    
        li.textContent = city + ": " + date.toLocaleDateString(cityList[city]);
    
        list.appendChild(li);
      }
    }
    
    window.onload = populateCities;
    <ul id="cities"></ul>