优化代码小技巧

636 阅读1分钟

1.数组方法Array. includes

可代替大量或语句。

要求:检测动物有没有

 function printAnimals(animal) {
            if (animal === 'dog' || animal === 'cat') {
                console.log(`I Have a ${animal}`);
            }
        }
        printAnimals('dog')

优化后可摆脱写或的尴尬

  function printAnimals(animal) {
            const animals = ['dog', 'cat', 'hamster']
            if (animals.includes(animal)) {
                console.log(animal);
            }
        }
        printAnimals('dog')

2.提前退出/提前返回

需求:没有动物抛出异常,有,就打印动物类型,名字,性别

 function printAnimalsDetails(animal) {
            var result = null
            if (animal) {
                if (animal.type) {
                    if (animal.name) {
                        if (animal.genter) {
                            result = `${animal.name} is a ${animal.genter} ${animal.type}`
                        } else {
                            result = 'no animal genter'
                        }
                    } else {
                        result = 'no animal name'
                    }
                } else {
                    result = 'no animal type'
                }
            } else {
                result = 'no animal'
            }
            return result
        }
        console.log(printAnimalsDetails());
        console.log(printAnimalsDetails({
            type: '狗',
            name: '旺财',
            genter: '公',
        }));

采用提前退出,提前返回优化代码

const printAnimalsDetails = ({
            type,
            name,
            genter
        } = {}) => {
            if (!type) return 'no animal type'
            if (!name) return 'no animal name'
            if (!genter) return 'no animal genter'
            return `${name} is a ${genter} ${type}`
        }
        console.log(printAnimalsDetails());
        console.log(printAnimalsDetails({
            type: '狗',
            name: '旺财',
            genter: '公',
        }));

3.对象字面量代替switch语句

  function printFruits(color) {
            switch (color) {
                case ' red':
                    return ['apple ']
                case 'yellow':
                    return ['banana']

                default:
                    return []
            }
        }
        console.log(printFruits(null));
        console.log(printFruits('yellow'));

对象字面量优化后

  const fruitsColor = {
            red: ['apple'],
            yellow: [' banana']
        }

        function printFruits(color) {
            return fruitsColor[color] || []
        }
        console.log (printFruits(null))
        console.Log(printFruits('yellow'))

4.默认参数结构map

原始代码

  var obj1 = {
            name: ' zs '
        }
        var obj2 = {
            name: 'ls'
        }
        var obj3 = {
            [obj2]: '22',
            [obj1]: '11',
        }
        // es5中方法,对象key:value形式.key默认是字符串,当不是字符串,会隐式调用tostring方法,把你转化为字符串
        //   var obj3 = {
        // '[object Object]': '22',
        // '[object Object]': '11',
        //   }
        console.log(obj3) //11,

map改写

ps:map在前篇有详细介绍

  const fruitsColor = new Map().set('red', [' apple']).set('yellow', ['banana'])

        function printFruits(color) {
            return fruitsColor.get(color) || []
            console.Log(printFruits(null))
            console.log(printFruits('yellow'))
        }

5.用上Array. some Array. every

every方法

需求:检测是否所有的水果都是红色

 //上需求检测是否所有的水果都是红色
        const fruits = [{
                    name: 'apple',
                    color: 'red'
                }, {
                    name: 'banana',
                    color: 'yellow'
                },]
                function test() {
                    const isAlLRed = fruits.every(f => f.color == 'red')
                 console.log(isAlLRed);
                }
                  test()

some方法

需求:检测是否所有的水果是否有红色

  const fruits = [{
            name: 'apple',
            color: 'red'
        }, {
            name: 'banana',
            color: 'yellow'
        }, ]

        function test() {
            const isAlLRed = fruits.some(f => f.color == 'red')
            console.log(isAlLRed);
        }
        test()