functiondestructrue({name = 'setsuna', gender = 'female', age = 18, spouse = 'haruki'}) { console.log(`my name is ${name}, I'm ${age} years old ${gender === 'female' ? 'girl' : 'boy'}, my lover is ${spouse}.`); }
destructrue({ age: 20, name: 'kazusa', });
// output: my name is kazusa, I'm 20 years old girl, my lover is haruki.
交换变量的值
平时我们实现变量值的交换往往需要借助第三个变量,但是通过解构我们可以实现这个功能:
1 2 3 4 5 6
// 变量交换 letx: number = 1,y: number = 2; [x, y] = [y, x]; // 多个变量的交换 leta: number = 1,b: number = 2,c: number = 3; [a,b,c] = [c,a,b];
// 使用扩展运算符进行的是深拷贝喵( •̀ ω •́ )✧ let arr = [1,2,3] let arr1 = [0,...arr,4];
let person = { name: 'haruki', gender: 'male', spouse: 'kazusa', } let whiteAlbum2 = {...person, job: 'journalist'};
我们还可以使用扩展运算符用于函数传参:
1 2 3 4 5 6
functionspreadOperation(...params: number[]) { console.log(`I get ${params[0]} and ${params[1]} and ${params[2]}`); } constarr: number[] = [1,2,3]; spreadOperation(111,222,...arr); // output: I get 111 and 222 and 1
// function bind method: return a new function which bind key word 'this' with param1 // 通过bind函数你还可以指定一些参数的值, 比如说 const bookNanHang = book.bind(NanHang, 23); const bookNanHang = book.bind(NanHang); bookNanHang(810, 'katsusa');