[JavaScript] Spread operator and Rest operator


❗️Spread and Rest


📒 Add the elements of an existing array into a new array

let addToArr = ['Hello', 'World!', 'JavaScript'];
let arr = ['...spread operator', 'and', ...addToArr1, 'rest operator'];

console.log(arr);

📒 Pass elements of an array as arguments to a function

function addThreeNums(x, y, z) {
  console.log(x + y + z);
}

let nums = [0, 1, 2];
addThreeNums(...nums);
let nums_4 = [0, 1, 2, 3];

addThreeNums(...nums_4);
addThreeNums関数は3つしか呼び出さないためnum 4の3番目の要素は無視されます.

📒 Copy arrays

let arr = [1, 2, 3];
let arr2 = [...arr]; // like arr.slice()

arr2.push(4);
console.log(arr);
console.log(arr2);

新しいアレイを作成してコピーするため、arrとarr 2の値は異なります.

📒 Concatenate arrays

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];

// arr1.concat(arr2);
arr1 = [...arr1, 'JavaScript', ...arr2];
console.log(arr1);

concatより柔軟です.

💡 REST: condense multiple elements into an array

function multiply(multiplier, ...theArgs) {
  return theArgs.map(function (element) {
    return multiplier * element;
  });
}

let arr = multiply(2, 1, 2, 3); 
//multiplier => 2 , ...theArgs => 1, 2, 3
console.log(arr); // [2, 4, 6]
ソース
  • MDN Web Docs
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
  • Luke Ruokaismaki
    https://medium.com/@luke_smaki/javascript-es6-spread-operator-and-rest-parameters-b3e89d112281
  • Poiemaweb.com
    https://poiemaweb.com/es6-extended-parameter-handling