传播和休息运算符
文章标签
运算符
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
1. 将两个数组合并在一起
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'
2. 创建数组的浅拷贝
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' ]
spread 也适用于对象,即使它们不是可迭代的。
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.
休息和传播的微妙区别: