const nums = [5,6,7]; const newNums = [1,2, nums[0],nums[1],nums[2]]; console.log(newNums); // [ 1, 2, 5, 6, 7 ] is reduced to const nums = [5,6,7]; const newNums = [1,2, ...nums]; console.log(newNums); // [ 1, 2, 5, 6, 7 ] console.log(...newNums); // 1 2 5 6 7
const arr1 = [1,2,3,4,5]; const arr2 = [6,7,8,9]; let nums = [...arr1,...arr2]; nums; // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] const firstname = "Peter"; const fullName = [...firstname,' ',"P."]; fullName; // [ 'P', 'e', 't', 'e', 'r', ' ', 'P.' ] console.log(...firstname); // 'P' 'e' 't' 'e' 'r'
const girl = { name: 'Melania', friends: ['Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya'] }; const frnz = [...girl.friends]; console.log(frnz); // [ 'Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya' ] console.log(girl.friends); // [ 'Alina', 'Alice', 'Ayesha', 'Anamika', 'Anaya' ]
let male = { "firstName": "Gangadhar", "lastName": "Shaktimaan" } let female = { "firstName": "Geeta", "lastName": "Vishwas" } let x = {...male, born: 1950}; let y = {...female, born: 1940}; x; // { firstName: 'Gangadhar', lastName: 'Shaktimaan', born: 1950 } y; // { firstName: 'Geeta', lastName: 'Vishwas', born: 1940 }``` ## Shallow Copy of objects: let male = { "firstName": "Gangadhar", "lastName": "Shaktimaan" } let character = {...male, firstName: 'Wonderwoman'}; male; // { firstName: 'Gangadhar', lastName: 'Shaktimaan' } character; // { firstName: 'Wonderwoman', lastName: 'Shaktimaan' } - First name for character object is changed although it was extracted from male object
スプレッド演算子とレスト演算子の構文の違い:
スプレッド演算子 => ... 代入演算子の右側で使用されます。
const nums = [9,4, ...[2,7,1]];
残り演算子 => ... 分割演算子を使用した代入演算子の左側に配置されます
const [x,y,...z] = [9,4, 2,7,1];
## Rest syntax collects all the elements after the last elements into an array. Doesn't include any skipped elements. - Hence, it should be the last element in the destructuring assignment. - There can be only one rest in any destructuring assignment.
ダイエットをしましょう = ['ピザ', 'バーガー','ヌードル','ロースト','寿司','ドーサ','ウッタパム'];
[最初、、、三番目、...その他] = ダイエット;
最初に;
3 番目;
その他;
- Rest also works with objects. Only difference is that elements will be collected into a new object instead of an arrray.
let days = { 'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6,'sun':7};
let {sat, sun, ...working} = days;
let off = {土、日};
働いています。 // { 月: 1、火: 2、水: 3、木: 4、金: 5 }
オフ; // { 土: 6、日: 7 }
- Although both look same, but they work differently based on where they are used.
レストとスプレッドの微妙な違い:
以上がスプレッド&レスト演算子の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。