JavaScript 编程中的好代码与坏代码

  1. console.log

我们现在有下面的代码:

 const foo = { name:"tom",   age:30, nervous:false }
 const bar = { name:"dick",  age:40, nervous:false }
 const baz = { name:"harry", age:50, nervous:true }

坏代码

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

坏结果

image-20181126232952086.png

好代码

console.log({foo, bar, baz})
image-20181126233226402.png

console.log 带有css样式的代码

console.log("%c My Frieds",'color:orange;font-weight:bold')
image-20181126233512246.png

输出在带表格的样式

console.table([foo, bar, baz])
image-20181126233901123.png

统计脚本运行时间

console.time(looper)

let i =0;
while( i < 100000) { i++ }

console.timeEnd(looper)  
image-20181126234300923.png

追踪调用栈

let sayBye = ()=> console.trace("Bye, Bey, LiSi") 

sayBye();
sayBye();
sayBye();    
image-20181126234616924.png
  1. destructuring(解构赋值)

    const turble = {
        name:"Bob",
        legs: 4,
        shell: true,
        type:"amphibious",
        meal:10,
        diet:"berries"
    }
    

    坏代码

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

    好代码:

    function feed({name, meal,diet}) {
        return `Feed ${name} ${meal} kiols of ${diet}`;
    }    
    

    或者

    function feed(animal){
        let {name, meal, diet} = animal;
        return `Feed ${name} ${meal} kiols of ${diet}`;
    }    
    
  2. 字符串模板

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

    坏代码:

    let bio = horse.name + " is a " + horse.size + " horse"
    

    好代码

    const { name, size}  = horse
    let bio = `${name} is a ${size} horse`
    

    更进一步,纯函数写法

    function horseAge(str, age){
        const  ageStr =  age > 5 ? "old":"young" ;
        return   `${str[0]}${ageStr} at ${age} years`;
    }
    
    const bio = horseAge`This horse is ${horse.age}`;
    console.log(bio)
    
  3. 扩展符的应用

    对象类型

    const pikachu = {
        name: "Pikachu"
    };
    const stats = {
        hp: 30,
        attack: 60,
        defense: 45
    }    
    

    坏代码

     pikachu["hp"] = stats.hp;
     pikachu["attack"] = stats.attack;
     pikachu["defense"] = stats.defense;
     
     或者
     
     const lvl0 = Object.assign(pikachu, stats);
     const lvl1 = Object.assign(pikachu, { hp: 45 });
    
    

    好代码

    const lvl0 = {...pikachu,...stats}   
    

    数组类型

    let pockmon = ['Arbok', 'Raichu', 'Sandshrw'];
    

    坏代码

    pockmon.push("Bulbasaur")
    pockmon.push("Metapod")
    pockmon.push("Weedle")
    

    好代码

    pockmon = [...pockmon, "Bulbasaur", "Metapod","Weedle"]
    // Shift
    pockmon = ["Bulbasaur", "Metapod","Weedle",...pokemon]
    
  4. 循环

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

    坏代码

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

    好代码

    const total = orders.reduce((acc, cur) => acc + cur);
    const withTax = orders.map(v => v * 1.1);
    const highValue = orders.filter(v => v > 100);
    
  5. async-await

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

    坏代码

    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 random();
        });
    };
    

    好代码

    const sumRandomAsyncNums = async () => {
      const first = await random();
      const second = await random();
      const third = await random();
        
      // or
      
      const randos = Promise.all([random(), random(), random()]);
        for (const r of await randos) {
        console.log(r);
      }
    };
    
    

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容