Skip to content

Instantly share code, notes, and snippets.

@wcang
Created January 19, 2015 17:41
Show Gist options
  • Save wcang/9ea6e52a24f06ad2c1f6 to your computer and use it in GitHub Desktop.
Save wcang/9ea6e52a24f06ad2c1f6 to your computer and use it in GitHub Desktop.
Exercise 13.1 for Eloquent Javascript
<style>
/* Defines a cleaner look for tables */
table { border-collapse: collapse; }
td, th { border: 1px solid black; padding: 3px 8px; }
th { text-align: left; }
</style>
<script>
var MOUNTAINS = [
{name: "Kilimanjaro", height: 5895, country: "Tanzania"},
{name: "Everest", height: 8848, country: "Nepal"},
{name: "Mount Fuji", height: 3776, country: "Japan"},
{name: "Mont Blanc", height: 4808, country: "Italy/France"},
{name: "Vaalserberg", height: 323, country: "Netherlands"},
{name: "Denali", height: 6168, country: "United States"},
{name: "Popocatepetl", height: 5465, country: "Mexico"}
];
function buildTable(data) {
// Your code here.
var table = document.createElement("table");
var row = document.createElement("tr");
var header = []
table.appendChild(row);
Object.keys(data[0]).forEach(function (header) {
var th = document.createElement("th");
th.textContent = header;
this.push(header);
row.appendChild(th);
}, header);
data.forEach(function (mountain) {
var tr = document.createElement("tr");
this.header.forEach(function (prop) {
var td = document.createElement("td");
td.textContent = mountain[prop];
this.appendChild(td);
}, tr);
this.table.appendChild(tr);
}, {table: table, header: header});
return table;
}
document.body.appendChild(buildTable(MOUNTAINS));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment