2016年12月18日日曜日

開発環境

Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 2(Browser)、Chapter 13(The Document Object Model)、Exercises(Build a Table)を取り組んでみる。

Exercises(Build a Table)

コード(Emacs)

JavaScript

'use strict';
let div = document.querySelector('#d0');
const 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"}
];
let buildTable = (data) => {
    let table = document.createElement('table');

    table.border = '1';
    let tr = document.createElement('tr');
    let keys = Object.keys(data[0]);
    keys.forEach((key) => {
        let th = document.createElement('th');
        th.textContent = key;
        tr.appendChild(th);
    });
    table.appendChild(tr);
    data.forEach((mountain) => {
        let tr = document.createElement('tr');
        keys.forEach((key) => {
            let td = document.createElement('td');
            if (!isNaN(Number(mountain[key]))) {
                td.style.textAlign = 'right';
            }
            td.textContent = mountain[key];
            tr.appendChild(td);
        });
        table.appendChild(tr);
    });
    return table;
};

div0.appendChild(buildTable(MOUNTAINS));

0 コメント:

コメントを投稿