JavaScript 这样写,以及不要那样写

97 阅读1分钟

翻译自 Fireship 视频

  1. 程序调试(console.log)

    const foo = { name: 'tom', age: 30, nervos: false};
    const bar = { name: 'dick', age: 40, nervos: false};
    const baz = { name: 'harry', age: 50, nervos: true};
    

    💩 Bad Code

    console.log(foo);
    console.log(bar);
    console.log(baz);
    

    bad1.png

    ✅ Good Code

    console.log({foo, bar, baz});
    
    // 样式
    console.log('%c My Friends', 'color: orange; font-weight: bold;')
    
    // 表格
    console.table([foo, bar, baz]);
    
    // 计时
    console.time('looper');
    let i = 0;
    while(i < 10000) { i++; }
    console.timeEnd('looper');
    
    // 堆栈
    const deleteMe = () => console.trace('bye bye database')
    deleteMe()
    

    good1.png

  2. 解构

    const turtle = {
       name: 'Bob 🐢',
       legs: 4,
       shell: true,
       type: 'amphibious',
       meal: 10,
       diet: 'berries'
    }
    

    💩 Bad Code

    function feed(animal) {
        return `Feed ${animal.name} ${animal.meal} kilos of ${animal.diet}`;
    }
    

    ✅ Good Code

    function feed({name, meal, diet}) {
        return `Feed ${name} ${meal} kilos of ${diet}`;
    }
    // 或者
    function feed(animal) {
        const {name, meal, diet} = animal;
        return `Feed ${name} ${meal} kilos of ${diet}`;
    }
    
  3. 模板字面量

    const horse = {
        name: 'Topher 🐴',
        size: large,
        skills: ['jousting', 'racing'],
        age: 7
    }
    

    💩 Bad Code

    let bio = horse.name + 'is a ' 
        + horse.size + ' horse skilled in ' 
        + horse.skills.join(' & ');
    

    ✅ Good Code

    const {name, size, skills} = horse;
    let bio = `${name} is a ${size} horse skilled in ${skills.join(' & ')}`
    
    // 或者
    
    function horseAge(str, age) {
        const ageStr = age >  5 ? 'old' : 'young';
        return `${str[0]}${ageStr} at ${age} years`;
    }
    const bio2 = horseAge`This horse is ${horse.age}`;
    
  4. 扩展运算符

    const pikachu = { name: 'Pikachu 🐱' };
    const stats = { hp: 40, attack: 60, defense: 45 };
    
    // 数组
    let pokemen = ['Arbok', 'Raichu', 'Sandshrew'];
    

    💩 Bad Code

    pikachu['hp'] = stats.hp;
    pikachu['attack'] = stats.attack;
    pikachu['defense'] = stats.defense;
    
    // 或者
    
    const lv10 = Object.assign(pikachu, stats);
    const lv11 = Object.assign(pikachu, { hp: 45 });
    
    // 数组
    pokemen.push('Bulbasaur');
    pokemen.push('Metapod');
    pokemen.push('Weedle');
    

    ✅ Good Code

    const lv10 = {...pikachu, ...stats};
    const lv11 = {...pikachu, { hp: 45 }};
    
    // 数组
    // push
    pokemen = [...pokemen, 'Bulbasaur', 'Metapod', 'Weedle'];
    // unshift
    pokemen = ['Bulbasaur', 'Metapod', ...pokemen, 'Weedle', ];
    
  5. 循环

    const orders = [500, 39, 99, 15, 223];
    

    💩 Bad Code

    const total = 0;
    const withTax = [];
    const highValue = [];
    for(int i = 0; i< orders.length; i++){
        // Reduce
        total += orders[i];
        // Map
        withTax.push(orders[i] * 1.1);
        // Filter
        if(orders[i] > 100){
            highValue.push(orders[i]);
        }
    }
    

    ✅ Good Code

    // Reduce
    const total = orders.reduce((acc, cur) => acc + cur);
    // Map
    const withTax = orders.map(v => v * 1.1);
    // Filter
    const highValue = orders.filter(v => v > 100);
    
  6. async 和 await

    const random = () => {
        return Promise.resolve(Math.random());
    }
    

    💩 Bad Code

    const sumRandomAsyncNums = () => {
        let first;
        let second;
        let third;
        
        return random()
            .then(v => {
                first = v;
                return random();
            })
            .then(v => {
                second = v;
                return random();
            })
            .then(v => {
                third = v;
                return first + second + third;
            })
            .then(sum => { 
                console.log(`Result ${sum}`)
            })
    }
    

    ✅ Good Code

    const sumRandomAsyncNums = async() => {
        const first = await random();
        const second = await random();
        const third = await random();
        
        console.log(`Result ${first + second + third}`)
    }