[やってみた]JavaScript MDN 初級チュートリアル バカ話ジェネレーター

前回に引き続き公式チュートリアルを進めています。今回はバカ話ジェネレーターを作りました。https://developer.mozilla.org/ja/docs/Learn/JavaScript/First_steps/Silly_story_generator

このチュートリアルでは以下の理解が問われていると感じました。
・HTMLのエレメントの値の取得
・jsにおける乱数生成
・文字列の操作(一致検索・置換など)
・while, if を利用した処理のコード実装
・(できると便利)正規表現

Rとかpythonと比べるとまだまだ慣れないので、一括置換のやり方がわからなかったり、乱数生成ってこれしか方法ないのかなとか思ったりしましたが、これから慣れていければいいなぁ。

ファイルはGitHubに置いておきます!
https://github.com/masayukeeeee/JS_training/tree/master/training_03

// set paragraph for generated story
var newStory = document.querySelector('.generatedStory');

// get button
var paramsSubmit = document.querySelector('.paramsSubmit')

// story format
var story = "It was 94 fahrenheit outside, so :insertx: went for a walk. When they got to :inserty:, they stared in horror for a few moments, then :insertz:. Bob saw the whole thing, but was not surprised - :insertx: weighs 300 pounds, and it was a hot day.";

// random elements
x_array = ["Willy the Goblin",
    "Big Daddy",
    "Father Christmas"
];

y_array = ["the soup kitchen",
    "Disneyland",
    "the White House"
];

z_array = ["spontaneously combusted",
    "melted into a puddle on the sidewalk",
    "turned into a slug and crawled away",
];

// define a function to replace :insert*: with random variable
function story_generator() {
    // declaration of variables
    var random_num = Math.floor(Math.random() * 3);
    console.log(random_num);
    var ins_len = ":insertx:".length;
    var regExp = /:insert[a-z]:/g;

    // copy 
    new_story = story;

    // get custom name
    var customName = document.querySelector('.customName').value;

    if (customName !== "") {
        new_story = new_story.replace("Bob", customName);
    }

    // replace /:insert[x-z]:/g with x_array element
    while (/:insertx:/.exec(new_story) !== null) {
        new_story = new_story.replace(":insertx:", x_array[random_num]);
    }

    while (/:inserty:/.exec(new_story) !== null) {
        new_story = new_story.replace(":inserty:", y_array[random_num]);
    }

    while (/:insertz:/.exec(new_story) !== null) {
        new_story = new_story.replace(":insertz:", z_array[random_num]);
    }

    // get country
    var country = document.getElementById('selectCountry').country.value;

    if (country === "UK") {
        new_story = new_story.replace("94", 94 - 32);
        new_story = new_story.replace("fahrenheit", "Celsius");
        new_story = new_story.replace("300", Math.round(300 * 0.0714286));
        new_story = new_story.replace("pounds", "stones");
    }

    newStory.textContent = new_story;
}

// set function on paramsSubmit button
paramsSubmit.addEventListener('click', story_generator);

この記事が参加している募集

#やってみた

36,946件