ES6之函数扩展

函数新增特性:

1.函数参数默认值:注意,函数参数写了默认值以后,他后面如果还有参数,必须也赋默认值。

	<script type="text/javascript">
			function test(a,b = "world"){
				console.log(a,b);
			}
			test("hello");  //hello world
			test("hello","Mike");  //hello Mike
	</script>

注意:一个参数作用域的问题

	<script type="text/javascript">
			let x = "hello";
			function test(x,y=x){
				console.log(x,y);
			}
			test("a");  //a a
			test();     //undefined  undefined

			function Test(c,y=x){
				console.log(c,y);
			}
			Test("a");    //a hello
	</script>

2.rest参数  :   就是把一系列参数转化为一个数组,注意:用了rest参数以后,不要用别的参数了。

	<script type="text/javascript">
			function rest(...arr){
				for(let v of arr){
					console.log(v);
				}
			}
			rest(1,2,3,4,"q","w",7);
	</script>

扩展运算符:实际上是rest参数的逆运算。

	<script type="text/javascript">
			console.log(...[1,2,4,5]);    //1 2 4 5
			console.log("a",...[1,2,3]);     //a 1 2 3
	</script>

3.箭头函数

	<script type="text/javascript">
			let arrow = v => v*2;
			console.log(arrow(2));  //4
	</script>

上面就是一个箭头函数的写法,v是参数,=>作为连接,v*2作为一个返回值,arrow就是函数名。

没有参数的话,这么写:

			let arrow2 = () => 5;
			console.log(arrow2());   //5

根据不同的使用场景来决定是否使用箭头函数。


4.尾调用:指某个函数的最后一步是调用另一个函数。

可以提高性能,如果一个函数嵌套函数比较严重的话,建议使用尾调用。

	<script type="text/javascript">
			function tail(x){
				console.log(x);
			}
			function one(x){
				return tail(x);
			}
			one("a");   //a
	</script>

上面就是尾调用。

猜你喜欢

转载自blog.csdn.net/sinat_40697723/article/details/82729717