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
展开运算符和剩余运算符的语法差异:
扩展运算符=> ...用于赋值运算符的 RHS。
const nums = [9,4, ...[2,7,1]];
休息运算符=> ...将位于具有解构的赋值运算符的 LHS
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.
let Diet = ['披萨', '汉堡','面条','烤','寿司','dosa','uttapam'];
让[第一,第三,...其他] =饮食;
首先;
第三;
其他;
- 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};
让 {周六、周日、...工作} = 天;
放开= {周六,周日};
工作; // { 周一:1,周二:2,周三:3,周四:4,周五:5 }
离开; // { 周六: 6, 周日: 7 }
- Although both look same, but they work differently based on where they are used.
休息和传播的微妙区别:
以上是传播和休息运算符的详细内容。更多信息请关注PHP中文网其他相关文章!