7、函数参数的默认值

136 阅读1分钟

7-1、函数参数的默认值

<script>
    // 1.认识函数参数的默认值
    // 调用函数的时候传参了,就用传递的参数;如果没传参,就用默认值
    // multiply(2, 1);
    // multiply(2);

    // 2.函数参数默认和的基本用法
    // const multiply = (x, y) => {
    //     if (typeof y === 'undefined') {
    //         y = 1;
    //     }
    //     return x * y;
    // };
    // console.log(multply(2, 2));

    // const multiply = (x, y = 1) => x * y;
    // console.log(multply(2, 2));
</script>

7-2、函数参数默认值的注意事项

<script>
    // 1.默认值的生效条件
    // 不传参数,或者明确的传递 undefined 作为参数,只有这两种情况下,默认值才会生效
    // const multiply = (x, y = 1) => x * y;
    // console.log(multiply(2, 0)); // 0
    // console.log(multiply(2, null)); // 0
    // console.log(multiply(2, undefined)); // 2
    // console.log(multiply(2)); // 2

    // 2.默认值表达式
    // 如果默认值是表达式,默认值表达式是惰性求值的

    // 3,设置默认值的小技巧
    // 函数参数的默认值,最好从参数列表的右边开始设置
    // const multiply = (x = 1, y) => x * y;
    // console.log(multiply(undefined, 2));

    // const multiply = (x, y = 1) => x * y;
    // console.log(multiply(2));

</script>

7-3、函数参数默认值的应用

<script>
    // 1.接收很多参数的时候
    // const logUser = (username = 'ZhangSan', age = 0, sex = 'male') => console.log(username, age, sex);
    // logUser('Alex', 18, 'male');
    // logUser();

    // 2.接收一个对象作为参数
    // const logUser = options => console.log(options.username, options.age, options.sex);

    // const logUser = ({ username = 'zhangsan', age = 0, sex = 'male' }={}) => console.log(username, age, sex);

    // logUser({
    //     username: 'alex',
    //     age: 18,
    //     sex: 'male'
    // });
    // logUser({ username: 'alex' });
    // { username = 'zhangsan', age = 0, sex = 'male' }
    // logUser({});
    // logUser();
    // { username = 'zhangsan', age = 0, sex = 'male' }=undefined
</script>