zoukankan      html  css  js  c++  java
  • 巧用&&和|| 让逻辑代码更简洁,逼格看起来更高一点(玩笑脸)

    通常当我们有一个需求 需要用到很多if else 进行条件筛选,例如:

     1 let level = 0;    
     2 
     3 if(score > 12){    
     4     level = 4;    
     5 }    
     6 else if(score > 10){    
     7     level = 3;    
     8 }    
     9 else if(score > 5){    
    10     level = 2;    
    11 }    
    12 else if(score > 0){    
    13     level = 1;    
    14 }    
    15 else {    
    16     level = 0;    
    17 } 

    通过判断score的大小来给level赋值

    这样写代码看起来很冗长,臃肿。 再看下面这种写法:

    let level = (score>12 && 4) || (score>10 && 3) || (score>5 && 2) || (score>0 && 1) || 0;

    一行代码搞定啦!

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    请你一定要记住:在js逻辑运算中,0、”“、null、false、undefined、NaN都会判为false,其他都为true;

  • 相关阅读:
    11.06第十次作业
    (构造方法私有化、this)10.29练习题
    10.23创造人
    10.16(RuPeng)游戏
    10.09
    作业9.25
    练习题
    (随机数之和)求一整数各位数之和1636050052王智霞
    两点之间的距离1636050052王智霞
    TabLayout 简单使用。
  • 原文地址:https://www.cnblogs.com/lml2017/p/10190850.html
Copyright © 2011-2022 走看看