美文网首页
JavaScript 编程中的好代码与坏代码

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

作者: HerrDu | 来源:发表于2018-11-27 09:59 被阅读0次
    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);
        }
      };
      
      

    相关文章

      网友评论

          本文标题:JavaScript 编程中的好代码与坏代码

          本文链接:https://www.haomeiwen.com/subject/vxwwqqtx.html