zoukankan      html  css  js  c++  java
  • 函数默认值

            <body>
            1. 默认值
            <script type="text/javascript">
                // bad
                function test(quantity) {
                  const q = quantity || 1;
                }
                
                // good
                function test(quantity = 1) {
                  ...
                }
            </script>
            <script type="text/javascript">
                doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
                
                // bad
                function doSomething(config) {
                  const foo = config.foo !== undefined ? config.foo : 'Hi';
                  const bar = config.bar !== undefined ? config.bar : 'Yo!';
                  const baz = config.baz !== undefined ? config.baz : 13;
                }
                
                // good
                function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
                  ...
                }
                
                // better
                function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { //这种是给不传参数的默认值
                    console.log(foo, bar)
                }
            </script>
            <script type="text/javascript">
                // 知识点: defaultProps
                // bad
                const Button = ({className}) => {
                    const classname = className || 'default-size';
                    return <span className={classname}></span>
                };
                
                // good
                const Button = ({className = 'default-size'}) => (
                    <span className={classname}></span>
                );
                
                // better
                const Button = ({className}) =>
                    <span className={className}></span>
                }
                
                Button.defaultProps = {
                    className: 'default-size'
                }
            </script>
            <script type="text/javascript">
                // 知识点: 缺少参数会进入这个方法,项目中我们可以利用这一点做些事情
                const required = () => {throw new Error('Missing parameter')};
                
                const add = (a = required(), b = required()) => a + b;
                
                add(1, 2) // 3
                add(1); // Error: Missing parameter.
            </script>
        </body>
  • 相关阅读:
    学习记录---KMP算法-部分匹配表理解
    关于GameObject无法禁用问题
    out用法
    关于Dictionary.TryGetValue的个人理解记录
    Transform.parent和Transform.root的区别
    Queue默认容量
    关于Camera Culling Mask
    MSVCP110.DLL没有被指定在WINDOWS上运行
    typeof instanceof 之间的区别总结
    Promise 使用心得
  • 原文地址:https://www.cnblogs.com/wangxi01/p/11590154.html
Copyright © 2011-2022 走看看