js function parameter default value

1 Basic usage

let f = (x = 1, y = 2) => {
    
    
    console.log('x:', x, 'y:', y);
}
f(); // x: 1 y: 2
f(100); // x: 100 y: 2
f(100, 200); // x: 100 y: 200
f(100, 200, 300); // x: 100 y: 200

2 Use destructuring assignment

let f = ({
    
     x= 1, y = 2 }) => {
    
     // 是等号不是冒号
    console.log('x:', x, 'y:', y);
}
f(); // 报错
f({
    
    }); // x: 1 y: 2
f({
    
     x: 100 }); // x: 100 y: 2
f({
    
     x: 100, y: 200 }); // x: 100 y: 200
f({
    
     x: 100, y: 200, z: 300 }); // x: 100 y: 200

3 Combine the two, double default

let f = ({
    
     x= 1, y = 2 } = {
    
    }) => {
    
    
    console.log('x:', x, 'y:', y);
}
f(); // x: 1 y: 2
f({
    
    }); // x: 1 y: 2
f({
    
     x: 100 }); // x: 100 y: 2
f({
    
     x: 100, y: 200 }); // x: 100 y: 200
f({
    
     x: 100, y: 200, z: 300 }); // x: 100 y: 200

Guess you like

Origin blog.csdn.net/weixin_43915401/article/details/112569692