2016年9月19日月曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 7(Data Structures)、38(Filtering Values)を取り組んでみる。

38(Filtering Values)

コード(Emacs)

HTML5

<label for="numbers0">
  Enter a list of numbers, seprated by spaces: 
</label>
<input id="numbers0" type="text" value="1 2 3 4 5 6 7 8">
<br>
<div id="output0"></div>

<script src="sample38.js"></script>

JavaScript

(function () {
    'use strict';
    var input_numbers = document.querySelector('#numbers0'),
        div_output = document.querySelector('#output0'),
        filterEvenNumbers,
        output;

    filterEvenNumbers = function (nums) {
        var result = [],
            i,
            max,
            num;

        for (i = 0, max = nums.length; i < max; i += 1) {
            num = nums[i];
            if (num % 2 === 0) {
                result.push(num);
            }
        }
        return result;
    };
    output = function () {
        var nums,
            evens;

        nums =input_numbers.value.split(' ')
            .map(function (x) {
                return parseFloat(x);
            });
        evens = filterEvenNumbers(nums);
        console.log(nums);
        div_output.innerText =
            'The even numbers are ' + evens.join(' ') + '.';
    };
    input_numbers.onchange = output;
    output();
}());

0 コメント:

コメントを投稿