ES2015

ES2015のサンプル集です。

by s_hiroshi

Babel + JSX

// arrow function
const num = [1, 2, 3, 4, 5];
const elem = [];
num.forEach(v => {
  elem.push(v + 1);
});
console.log(elem);

// 引数配列展開
const arr = [1, 2, 3];
(function(x, y, z) {
  console.log(x + y + z);
}(...arr));

// for .. of
const str = 'sm00th';

for (const chr of str) {
  console.log(chr); // 's', 'm', '0', '0', 't', 'h'
}

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let total = 0;
for (const n of nums) {
  total += n;
}
console.log(total)

// イテレーター
function makeIterator(array) {
  var nextIndex = 0;

  return {
    // nextはオブジェクトを返す
    next: function() {
      if (nextIndex < array.length) {
        return {
          value: array[nextIndex++],
          done: false
        }
      } else {
        return {
          done: true
        };
      }
    }
  }
}

console.log('-----')
var it = makeIterator(['yo', 'ya']);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
console.log(it.next().value);
console.log('-----');