您的位置:首页 > Web前端 > JavaScript

写好 JS 条件语句的 5 条守则

2019-01-15 10:04 330 查看

总结:
1.多重判断时使用 Array.includes

function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}
}

2.更少的嵌套,尽早 return
3.使用默认参数和解构

// 解构 - 仅仅获取 name 属性
// 为其赋默认值为空对象
function test({name} = {}) {
console.log (name || 'unknown');
}
// test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

4.倾向于遍历对象而不是 Switch 语句
(1)对象遍历:

const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
(2)使用Map:
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);

function test(color) {
return fruitColor.get(color) || [];
}
(3)使用Array.filter:
const fruits = [
{ name: 'apple', color: 'red' },
{ name: 'strawberry', color: 'red' },
{ name: 'banana', color: 'yellow' },
{ name: 'pineapple', color: 'yellow' },
{ name: 'grape', color: 'purple' },
{ name: 'plum', color: 'purple' }
];

function test(color) {
return fruits.filter(f => f.color == color);
}

5.对 所有/部分 判断使用 Array.every & Array.some
原文地址:https://mp.weixin.qq.com/s/OMYSRsyHPIQD1UD5QqWPgQ

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: