[JavaScript] Spread operator and Rest operator
9501 ワード
❗️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]
ソース
let addToArr = ['Hello', 'World!', 'JavaScript'];
let arr = ['...spread operator', 'and', ...addToArr1, 'rest operator'];
console.log(arr);
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);
let arr = [1, 2, 3];
let arr2 = [...arr]; // like arr.slice()
arr2.push(4);
console.log(arr);
console.log(arr2);
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
// arr1.concat(arr2);
arr1 = [...arr1, 'JavaScript', ...arr2];
console.log(arr1);
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]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://medium.com/@luke_smaki/javascript-es6-spread-operator-and-rest-parameters-b3e89d112281
https://poiemaweb.com/es6-extended-parameter-handling
Reference
この問題について([JavaScript] Spread operator and Rest operator), 我々は、より多くの情報をここで見つけました https://velog.io/@jungjaedev/Javascript-spread-operator-and-rest-operatorテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol