Skip to content

Commit ee0ff3c

Browse files
committed
feat(es6): 新增剩余参数
1 parent 9d75a91 commit ee0ff3c

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

src/residual-parameters.js

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
//++++++++++++++++++++++++++++++++++++++++++++++++
2+
//函数参数的默认值
3+
function powerOf(base,exponent = 2) {
4+
return Math.pow(base,exponent)
5+
}
6+
7+
console.log(powerOf(2));
8+
console.log(powerOf(2, undefined));
9+
console.log(powerOf(2, 3));
10+
11+
var double = (value = 0) => value * 2
12+
console.log(double());
13+
console.log(double(2));
14+
15+
//对象参数默认值
16+
// var defaultOption = {
17+
// brand: 'volvo',
18+
// make: 2019
19+
// }
20+
// function carFactory(option = defaultOption) {
21+
// console.log(option.brand);
22+
// console.log(option.make);
23+
// }
24+
// carFactory()
25+
// //volvo
26+
// //2019
27+
//
28+
// //如果传入一个对象参数,则所有的默认值都会失效
29+
// carFactory({})
30+
// // undefined
31+
// // undefined
32+
//
33+
// carFactory({make: 2010})
34+
// // undefined
35+
// // 2010
36+
37+
//与提供一个默认参数相比,更好的办法是使用解构,并在解构模式中为每一个属性指定默认值
38+
function carFactory({brand = 'volvo',make = 2019}) {
39+
console.log(brand);
40+
console.log(make);
41+
}
42+
43+
// carFactory({})
44+
// // volvo
45+
// // 2019
46+
//
47+
// carFactory({make: 2010})
48+
// // volvo
49+
// // 2010
50+
//
51+
// carFactory()
52+
// //Exception
53+
54+
55+
// 添加一个空对象作为默认值可避免该问题,因为解构空对象时已经提供了默认值
56+
function carFactory({brand = 'volvo',make = 2019} = {}) {
57+
console.log(brand);
58+
console.log(make);
59+
}
60+
61+
carFactory()
62+
// volvo
63+
// 2019
64+
65+
//只想在某个函数中提取对象的某些属性作为参数,可以通过解构提前显式地引用这些属性
66+
var getCarProductModel = ({brand,make,model} = {})=>({
67+
sku: brand + ':' + make + ':' + model,
68+
brand,
69+
make,
70+
model
71+
})
72+
73+
var car = {
74+
brand: 'volvo',
75+
make: 2019,
76+
// model: '201',
77+
price: 280000,
78+
color: 'red'
79+
}
80+
console.log(getCarProductModel(car));
81+
console.log(getCarProductModel({}));
82+
console.log(getCarProductModel());
83+
84+
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
85+
//剩余参数
86+
//在函数的最后一个参数前添加...可以将该参数转变为一个特殊的剩余参数。
87+
//当剩余参数是函数中的唯一参数时,它会获取所有传入函数的参数
88+
// function join(...list) {
89+
// return list.join(',')
90+
// }
91+
// console.log(join('first', 'second', 'third'));
92+
93+
// var join = (...list) => list.join(',')
94+
// console.log(join('first', 'second', 'third'));
95+
96+
//剩余参数前面的参数不会包含在 list 参数中
97+
function join(separator,...list) {
98+
return list.join(separator)
99+
}
100+
101+
console.log(join(';', 'first', 'second', 'third'));

0 commit comments

Comments
 (0)