JS ES6 function extension

1. Specify default values ​​for function parameters

function fn(a = 10, b =20){
    
    
	console.log(a + b); // 30
}
fn()

2. The rest parameter of the function

The rest parameter is in the form of ("...variable name"), which is used to obtain the redundant parameters of the function, so that there is no need to use the arguments object. The variable with the rest parameter is an array, and the variable puts the extra parameters into the array.

function sum(){
    
    
	var args = arguments;
	var res = 0;
	for(var i = 0; i<args.length;i++){
    
    
		res += args[i];
	}
	console.log(res);
}
sum(1,2,3,4,5,6)	

After the change

function sum(...arr){
    
    
	var res = 0;
	for(var i=0; i<arr.length;i++){
    
    
	res += arr[i];
}
	console.log(res);
}
sum(10,1,2,3,4,5)		

3. Arrow function

Use the arrow "=>" to define the function

const fn = a => a;
const fn2 = function (a){
    
    
	return a;
};
console.log(fn(1));
console.log(fn(2));	

```javascript
const fn = (a, b) => a + b;
console.log(fn(1, 2)); // 3

const fn = (a, b) => {
    
    
	a = a * 2;
	b = b * 3;
	return a + b;
};	
console.log(fn(1, 2)); // 6

The arrow function does not have its own this object, so when it is used, its internal this is the object of the environment where it is defined, not the object of the environment where it is used.
You cannot use call apply bind for an arrow function to change the direction of this
inside. There is no arguments object in the arrow function body. If you want to use it, you can use the Rest parameter instead.

function fn (){
    
    
	setTimeout(() => {
    
    
		console.log(arguments);
	},1000)
	}
	fn(1,2,3)	

It cannot be used as a constructor, and the new command cannot be used, otherwise an error will be thrown.

const Fn = (a, b) => a + b;
const f = new Fn(1, 2);

Arrow functions cannot be used as generators

Guess you like

Origin blog.csdn.net/weixin_43176019/article/details/109180817