配列の分割代入(ES6)

配列の分割代入

/**
 * 配列の分割代入(ES6)
 */

//ES2015 before ---------------------------------------------
function arr1(){
    var data = [56, 40, 26, 82];
    document.getElementById('hoge1').textContent = data[0] + ', ' + data[1] + ', ' + data[2] + ', ' + data[3];
}
arr1();


//ES2015 after 分割代入---------------------------------------------
function arr2(){
    let data = [57, 41, 27, 83];
    let [x0, x1, x2, x3] = data;
    document.getElementById('hoge2').textContent = x0 + ', ' + x1 + ', ' + x2 + ', ' + x3;
}
arr2();

//スプレッド(…)演算子を使うと残りの要素すべてまとめて配列として切り出せる
function arg3(){
    let data = [4, 6, 9, 10, 20, 50];
    let [x0, x1, ...oth] = data;
    document.getElementById('hoge3').textContent = x0 + ', ' + x1 + ', ' + oth;
}
arg3();

See the Pen pebwrZ by nwstcode (@nwst) on CodePen.

TagTimes

Simple time tracking tool
Developed by Namu Works