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
Perbezaan dalam sintaks operator hamparan dan rehat:
Operator sebaran => ... digunakan pada RHS pengendali tugasan.
nombor const = [9,4, ...[2,7,1]];
Pengendali rehat => ... akan berada di LHS pengendali tugasan dengan memusnahkan
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.
biar diet = ['piza', 'burger','mi','panggang','sushi','dosa','uttapam'];
biar [pertama, ,ketiga, ...lain] = diet;
pertama;
ketiga;
yang lain;
- Rest also works with objects. Only difference is that elements will be collected into a new object instead of an arrray.
hari biarkan = { 'mon':1,'sel':2,'wed':3,'thu':4, 'jum':5, 'sab':6, 'sun':7};
biarkan {duduk, matahari, ...bekerja} = hari;
lepaskan = {sat, sun};
bekerja; // { isn: 1, tue: 2, wed: 3, thum: 4, fri: 5 }
padam; // { Sabtu: 6, matahari: 7 }
- Although both look same, but they work differently based on where they are used.
Perbezaan Halus b/w Rehat & Hampar:
Atas ialah kandungan terperinci Operator Spread & Rest. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!