Function parameters
Uncaught SyntaxError: Identifier ‘x’ has already been declared. 错 误 : Uncaught SyntaxError: Declared Identifier ‘x’ has already been declared. 错 误 : Uncaught SyntaxError: Declared Identifier ‘x’ has been declared
function fun1(x = 1, y = 2) {
// let x = 3; Uncaught SyntaxError: Identifier 'x' has already been declared. // Declared variables are declared by default, so cannot be declared again with let or const
return x*y;
};
console.log(fun1(5));
Copy the code
Uncaught SyntaxError: Duplicate parameter name not allowed in this context
function foo(name,name='xiaoyu') {
Uncaught SyntaxError: Duplicate parameter name not allowed in this context
};
Copy the code
3, deconstruction assignment method is used to transfer the default parameters, avoid fun1 methods don’t write only write y parameter x times wrong
function fun2({n=6,m=6} = {}) { // Use the destruct assignment method to pass the default arguments, avoiding the error of writing y instead of x in fun1
console.log(n*m);
};
fun2({m:8});
fun2();
Copy the code
4, the default value parameter can only be set to the tail parameter, otherwise when calling the method can not omit and need to pass again manually
function fn3(x,y=4,z) {
console.log(x,y,z);
};
fn3(3.5); // Result: 3 5 undefined
fn3(3.4.5);
Copy the code
5. The extension operator takes arguments of indefinite length and stores the extra arguments in an array object
function fn4(p1,p2,... pn) {
console.log(p1,p2,pn);
};
fn4(3.5.7.8.9.Awesome!);
Copy the code
Arrow function
Syntax: function name = (argument) =>{function body; };
- Omit () when there is only one parameter
- If the body of a function is only one sentence, omit {}
- If the body of a function has only one statement and is a return statement, return can be omitted
fn1 = name= >name; / / is equivalent to function fn1(name) { return name; } fn2 = (name,age) = > name+'The age of is'+age+', '; fn3 = name= >console.log(My name is:+name); Copy the code
- Arrow functions with no arguments cannot be omitted ()
fn1 = name= >name; / / is equivalent to function fn1(name) { return name; } fn2 = (name,age) = > name+'The age of is'+age+', '; fn3 = name= >console.log(My name is:+name); Copy the code
- {} must be used when the body of a function has more than one line
- You can use default value arguments, structure assignment arguments, and variable length arguments
- The this object in the body of the function is the object that was defined, not the object that was used
let name = 'doc1' let arr = { name :'doc2'.fo1:function(){ name :'doc3'.console.log(this.name); // Result: doc2}}; arr.fo1();Copy the code