JS编码技巧

### 避免`if`过长

判断值满足多个条件

```javascript
// Longhand
if (value === 'a' || value === 'b' || value === 'c') { ... }

// Shorthand
if (['a', 'b', 'c'].includes(value)) { ... }

可选链接(?.)

检查对象的某些属性是否存在

// Longhand
const test = { a: { b: { c: 1 } } }
if (!!test.a && !!test.a.b && !!test.a.b.c) { ... }

// Shorthand
if (!!test?.a?.b?.c) { ... }

简化循环

// Longhand
for (var i = 0; i < testData.length; i++)

// Shorthand
for (let i in testData) or  for (let i of testData)

三元操作符实现多函数调用

// Longhand
var test1 = 1;
if (test1 == 1) {
  test2();
} else {
  test3();
}
// Shorthand
(test1 === 1? test2:test3)();

switch简化

// Longhand
switch (data) {
  case 1:
    test1();
  break;
  case 2:
    test2();
  break;
  case 3:
    test();
  break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test
};
data[something] && data[something]();

使用||运算符给变量指定默认值

let imagePath;
let path = getImagePath();
if (path !== null && path !== undefined && path !== '') {
    imagePath = path;
} else {
    imagePath = 'default.jpg';
}
//Shorthand
let imagePath = getImagePath() || 'default.jpg';

使用&&运算符简化if语句

在某个条件为真时调用

//Longhand
if (isLoggedin) {
    goToHomepage();
 }
//Shorthand
isLoggedin && goToHomepage();

移除对象属性

let obj = {x: 45, y: 72, z: 68, p: 98};
// Longhand
delete obj.x;
delete obj.p;
console.log(obj); // {y: 72, z: 68}
// Shorthand
let {x, p, ...newObj} = obj;
console.log(newObj); // {y: 72, z: 68}

解构赋值

1.对于name的多次引用,效果会特别明显

// before
[{name: 'xxx'}].map(item => item.name)
// after
[{name: 'xxx'}].map(({name}) => name)

2.别名取值,适用于想创建与属性名称不同的变量

// identifier 是要访问的属性的名称,aliasIdentifier 是变量名称
const { identifier: aliasIdentifier } = expression;

3.动态属性,适用于使用动态名称提取到变量属性,属性名称在运行时已知

const products = {
    1: {
        title: "Nike Air Zoom Pegasus 38",
        price: 120,
    },
    2: {
        title: "Nike Air Zoom Alphafly NEXT%",
        price: 275,
    },
    3: {
        title: "Nike Zoom Fly 4",
        price: 89.0,
    },
};
const productKey = "1";
const { [productKey]: product } = products;
console.log(product); // { title: 'Nike Air Zoom Pegasus 38', price: 120 }

4.对象结构中的Rest,适用于收集未被解构模式拾取的剩余可枚举属性键

const product = {
    title: "Nike Air Zoom Pegasus 38",
    price: 120,
    quantity: 5,
    category_id: 1,
    reviews: 9830,
    total: 45,
};
const { title, ...others } = product;
console.log(others); // { price: 120, quantity: 5, category_id: 1, reviews: 9830, total: 45 }

5.默认值

const RGBA = [255, 34];
const [R, G, B = 0, A = 1] = RGBA;
console.log(R); // 255
console.log(G); // 34
console.log(B); // 0
console.log(A); // 1

使用策略模式替换胖分支

当if-else或者switch-case分支过多时可以使用策略模式将各个分支独立出来

// before
function getPrice(tag, originPrice) {
    // 新人价格
    if(tag === 'newUser') {
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    }
    // 返场价格
    if(tag === 'back') {
         return originPrice > 200 ? originPrice - 50 : originPrice
    }
    // 活动价格
    if(tag === 'activity') {
        return originPrice > 300 ? originPrice - 100 : originPrice
    }
}
// after
const priceHandler = {
    newUser(originPrice){
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    },
    back(originPrice){
        return originPrice > 200 ? originPrice - 50 : originPrice
    },
    activity(originPrice){
         return originPrice > 300 ? originPrice - 100 : originPrice
    }
}

function getPrice(tag, originPrice){
    return priceHandler[tag](originPrice)
}

分解条件表达式

对于带有负责逻辑的条件表达式,可将每个分支条件分解成新函数,以此:

  • 提高可读性
  • 突出条件逻辑,更清楚的表明每个分支的作用
  • // before
    if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd))
    charge = quantity * plan.summerRate;
    else
    charge = quantity * plan.regularRate + plan.regularServiceCharge;
    
    // after
    if (summer()) {
      charge = summerCharge();
    } else {
      charge = regularCharge();
    }
    function summer() {
        return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
    }
    function summerCharge() {
        return quantity * plan.summerRate;
    }
    function regularCharge() {
        return quantity * plan.regularRate + plan.regularServiceCharge;
    }
    
    // 进一步优化(使用三元运算符)
    charge = summer() ? summerCharge() : regularCharge();
    function summer() {
        return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
    }
    function summerCharge() {
        return quantity * plan.summerRate;
    }
    function regularCharge() {
        return quantity * plan.regularRate + plan.regularServiceCharge;
    }
    

    合并条件表达式

    适用于检查条件各不相同,最终行为却一致,则应该使用“逻辑或”和“逻辑与”将他们合并为一个条件表达式

  • // before
    if (anEmployee.seniority < 2) return 0;
    if (anEmployee.monthsDisabled > 12) return 0;
    if (anEmployee.isPartTime) return 0;
    // after
    if (isNotEligableForDisability()) return 0;
    function isNotEligableForDisability() {
        return ((anEmployee.seniority < 2)
                || (anEmployee.monthsDisabled > 12)
                || (anEmployee.isPartTime));
    }
    

    将查询函数和修改函数分离

    如果遇到一个“既有返回值又有副作用”的函数,此时可以将查询动作从修改动作中分离出来。

  • // before
    function alertForMiscreant (people) {
        for (const p of people) {
            if (p === "Don") {
                setOffAlarms();
                return "Don";
            }
            if (p === "John") {
                setOffAlarms();
                return "John";}
        }
        return "";
    }
    const found = alertForMiscreant(people);
    // after
    function findMiscreant (people) {
        for (const p of people) {
            if (p === "Don") {
                return "Don";
            }
            if (p === "John") {
                return "John";
            }
        }
        return "";
    }
    function alertForMiscreant (people) {
        if (findMiscreant(people) !== "") setOffAlarms();
    }
    
    const found = findMiscreant(people);
    alertForMiscreant(people);
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shumabaobei1214

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值