当我们想根据某个值得到某些数据时,如:根据 color 打印出水果:
function test(color) {
// 使用条件语句来寻找对应颜色的水果
switch (color) {
case 'red':
return ['apple', 'strawberry'];
case 'yellow':
return ['banana', 'pineapple'];
case 'purple':
return ['grape', 'plum'];
default:
return [];
}
}
// test results
test(null); // []
test('yellow'); // ['banana', 'pineapple']
switch语法可以实现,但美中不足处是代码有些冗余,我们可以尝试使用对象遍历实现相同的结果
const fruitColor = {
red: ['apple', 'strawberry'],
yellow: ['banana', 'pineapple'],
purple: ['grape', 'plum']
};
function test(color) {
return fruitColor[color] || [];
}
或者可以使用Map实现
const fruitColor = new Map()
.set('red', ['apple', 'strawberry'])
.set('yellow', ['banana', 'pineapple'])
.set('purple', ['grape', 'plum']);
function test(color) {
return fruitColor.get(color) || [];
}
Map是一种在 ES2015 规范之后实现的对象类型,详细了解点击
根据具体场景,选用以上三种方法,会让你的代码更简洁易维护,加油!